1
votes

Forme réactive angulaire. Mat Date Picker n'envoie pas la date à Firebase

J'ai créé le formulaire réactif ci-dessous et le "contractDate" ne pousse pas la date à Fire base.

Tout le reste fonctionne comme prévu. Quelqu'un peut-il m'indiquer dans la bonne direction ce qui ne va pas avec le code?

Juste pour ajouter quand je change le (formControlName = "contractDate") en autre chose que "contractDate", la colonne de firebase est envoyé mais vide.

HTML pour le composant client

import { Injectable } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import * as _ from 'lodash';

@Injectable({
  providedIn: 'root'
})
export class ClientsService {

  constructor(private firebase: AngularFireDatabase) { }

  clientsList: AngularFireList<any>;

  form: FormGroup = new FormGroup({
    $key: new FormControl(null),
    fullName: new FormControl('', Validators.required),
    email: new FormControl('', Validators.email),
    mobile: new FormControl('', [Validators.required, Validators.minLength(8)]),
    address: new FormControl('', Validators.required),
    gender: new FormControl('3'),
    location: new FormControl(0, Validators.required),
    contractDate: new FormControl(''),
    notes: new FormControl (''),
});

initializeFormGroup() {
  this.form.setValue({
    $key: null,
    fullName: '',
    email: '',
    mobile: '',
    address: '',
    gender: '3',
    location: '',
    contractDate: '',
    notes: '',
  });
}

getClients() {
  this.clientsList = this.firebase.list('clients');
  return this.clientsList.snapshotChanges();
}

insertClients(clients) {
  this.clientsList.push({
    fullName: clients.fullName,
    email: clients.email,
    mobile: clients.mobile,
    address: clients.address,
    gender: clients.gender,
    location: clients.location,
    contractDate: clients.contractDate,
    notes: clients.notes
  });
}

updateClients(clients) {
  this.clientsList.update(clients.$key,
    {
      fullName: clients.fullName,
      email: clients.email,
      mobile: clients.mobile,
      address: clients.address,
      gender: clients.gender,
      location: clients.location,
      contractDate: clients.contractDate,
      notes: clients.notes

    });
  }

  deleteClients($key: string) {
    this.clientsList.remove($key);
  }

  populateForm(clients: any) {
    this.form.setValue(_.omit(clients, 'locationName'));
  }
}

clients.component.ts

import { Component, OnInit } from '@angular/core';
import { MatDialogRef } from '@angular/material';

import { ClientsService } from 'src/app/shared/clients.service';
import { LocationService } from 'src/app/shared/location.service';
import { NotificationService } from 'src/app/shared/notification.service';



@Component({
  selector: 'app-clients',
  templateUrl: './clients.component.html',
  styleUrls: ['./clients.component.css']
})
export class ClientsComponent implements OnInit {

  constructor(private service: ClientsService,
              private locationService: LocationService,
              private notificationService: NotificationService,
              public  dialogRef: MatDialogRef<ClientsComponent>) { }

  ngOnInit() {
    this.service.getClients();
  }

  onClear() {
    this.service.form.reset();
    this.service.initializeFormGroup();
  }

  onSubmit() {
    if (this.service.form.valid) {
      this.service.insertClients(this.service.form.value);
      this.service.form.reset();
      this.service.initializeFormGroup();
      this.notificationService.sucess('Saved successfully!');
      this.onClose();
    }
  }

  onClose(){
    this.service.form.reset();
    this.service.initializeFormGroup();
    this.dialogRef.close();
  }
}

clients.service.component.ts

<form [formGroup]="service.form" class="normal-form" (submit)="onSubmit()">
    <mat-grid-list cols="2" rowHeight="400px">
        <mat-grid-tile>
          <div class="controles-container">
            <input type="hidden" formControlName="$key">
            <mat-form-field>
              <input formControlName="fullName" matInput placeholder="Full Name">
              <mat-error>Full Name is missing</mat-error>
            </mat-form-field>
            <mat-form-field>
              <input formControlName="email" matInput placeholder="Email">
              <mat-error>Email is missing</mat-error>
            </mat-form-field>
            <mat-form-field>
              <input formControlName="mobile" matInput placeholder="Mobile">
              <mat-error *ngIf="service.form.controls['mobile'].errors?.required">Mobile is missing.</mat-error>
              <mat-error *ngIf="service.form.controls['mobile'].errors?.minlength">Minimum 8 charactors needed.</mat-error>
            </mat-form-field>
            <mat-form-field>
              <input formControlName="address" matInput placeholder="Address">
              <mat-error>Address is missing</mat-error>
            </mat-form-field>
          </div>
        </mat-grid-tile>
        <mat-grid-tile>
          <div class="controles-container1">
            <mat-form-field>
              <mat-select formControlName="location" matInput placeholder="Location">
                <mat-option>None</mat-option>
                <ng-container *ngFor="let location of locationService.array">
                  <mat-option value="{{location.$key}}">{{location.name}}</mat-option>
                </ng-container>
              </mat-select>
            </mat-form-field>
            <mat-form-field>
              <input formControlName="contractDate" matInput [matDatepicker]="picker" placeholder="Contract Date">
              <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
              <mat-datepicker #picker></mat-datepicker>
            </mat-form-field>
            <div class="add-bottom-padding">
                <mat-radio-group formControlName="gender">
                  <mat-radio-button value="1">Male</mat-radio-button>
                  <mat-radio-button value="2">Female</mat-radio-button>
                  <mat-radio-button value="3">Other</mat-radio-button>
                </mat-radio-group>
              </div>
            <div>
            <mat-form-field class="add-bottom-padding" appearance="outline">
              <textarea formControlName="notes" matInput placeholder="Notes"></textarea>
            </mat-form-field>
          </div>
          <div class="button-row">
            <button mat-raised-button color="primary" type="submit" [disabled]="service.form.invalid" >Save</button>
            <button mat-raised-button color="warn" (click)="onClear()">Clear</button>
          </div>
          </div>
        </mat-grid-tile>
      </mat-grid-list>
</form>

Merci beaucoup d'avance.


0 commentaires

5 Réponses :


0
votes
  1. Veuillez changer le service privé: ClientsService en service public: ClientsService et réessayer
  2. Et quelle date devez-vous envoyer à la base de feu? Le sélecteur de date renvoie la date au format de chaîne comme celui-ci Mon 11 novembre 2019 00:00:00 GMT + 0400 (heure normale d'Arménie)

1 commentaires

Salut merci d'avoir répondu. 1. Ne fonctionne pas. J'ai essayé ça avant. Format 2.EU.



0
votes

vous pouvez essayer celui-ci pour

  1. remplacez votre entrée par ceci
  2. dans votre ts importez DatePipe de '@ angular / common' et ajoutez-le dans le constructeur
  3. private datePipe: DatePipe
  4. et mettez cette fonction dans vos ts
onSelectContractDate(event) {
const firebaseDate = this.datePipe.transform(event.value, 'YYYY-MM-DD');
this.service.form.get('contractDate').patchValue(firebaseDate);
}


2 commentaires

Merci Ashot, cependant, votre solution est de gâcher le modal que j'ai placé sur le formulaire réactif. Quelqu'un peut-il expliquer pourquoi seul le datapicker n'est pas poussé vers Firebase, mais quoi que ce soit d'autre? Très étrange!


Compris, pouvez-vous vérifier ce lien, peut-être le même problème stackoverflow.com/questions/45999710/...



2
votes

Tout d'abord GRAND merci à Ashot de m'avoir pointé dans la bonne direction!

Pour ajouter le sélecteur de date à Firebase, vous devez formater la date. Étapes ci-dessous.

Ajoutez d'abord DatePipe au tableau de fournisseurs app.module.ts.

Puis injectez le DatePipe dans le constructeur de votre service.ts

La dernière chose est de mettre à jour les fonctions avec DatePipe, où votre sélecteur de date met à jour / insère la date. Quelque chose comme: this.datePipe.transform (clients.contractDate, 'aaaa-MM-jj')

Merci!


0 commentaires

0
votes

Ou vous pouvez ajouter .toDate () à votre date depuis Firebase

doc


0 commentaires

0
votes

essayez contractDate: clients.contractDate.toJSON (),

au lieu de contractDate: clients.contractDate,


0 commentaires