【问题标题】:Reactive Form Angular. Mat Date Picker does not sent the date to Firebase反应形式角。 Mat Date Picker 不会将日期发送到 Firebase
【发布时间】:2019-11-24 20:34:13
【问题描述】:

我已经创建了下面的响应式表单,并且“contractDate”不会将日期推送到 Fire base。

其他一切都按预期工作。有人可以指出正确的方向吗?代码有什么问题?

当我将 (formControlName="contractDate") 更改为“contractDate”以外的任何其他内容时添加,firebase 中的列已发送但为空。

客户端组件的 HTML

<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>

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

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'));
  }
}

非常感谢您。

【问题讨论】:

    标签: angular firebase angular-material


    【解决方案1】:

    首先非常感谢 Ashot 为我指明了正确的方向!

    要将日期选择器添加到 Firebase,您必须格式化日期。下面的步骤。

    首先将 DatePipe 添加到 app.module.ts providers 数组中。

    然后将 DatePipe 注入到你的 service.ts 中的构造函数

    最后一件事是使用 DatePipe 更新函数,您的日期选择器正在更新/插入日期。类似于:this.datePipe.transform(clients.contractDate, 'yyyy-MM-dd')

    谢谢!

    【讨论】:

      【解决方案2】:
      1. 请把private service: ClientsService改成public service: ClientsService再试一次
      2. 您需要将什么日期发送到火力基地?日期选择器以字符串格式返回日期,如Mon Nov 11 2019 00:00:00 GMT+0400 (Armenia Standard Time)

      【讨论】:

      • 您好,感谢您的回复。 1. 不工作。以前试过这个。 2.欧盟格式。
      【解决方案3】:

      你可以试试这个

      1. 用这个替换你的输入 &lt;input (dateChange)="onSelectContractDate($event)" matInput [matDatepicker]="picker" placeholder="Contract Date"&gt;
      2. 在你的 ts 中导入 DatePipe from '@angular/common' 并将其添加到构造函数中
      3. private datePipe: DatePipe
      4. 并将此功能放入您的 ts 中
      onSelectContractDate(event) {
      const firebaseDate = this.datePipe.transform(event.value, 'YYYY-MM-DD');
      this.service.form.get('contractDate').patchValue(firebaseDate);
      }
      

      【讨论】:

      • 谢谢Ashot,但是,您的解决方案弄乱了我放置反应表单的模态。有人可以解释为什么只有数据选择器没有被推送到火力基地,而其他任何东西都是?很奇怪!
      • 知道了,请检查一下这个链接,可能是同样的问题stackoverflow.com/questions/45999710/…
      【解决方案4】:

      或者您可以在 Firebase 中将 .toDate() 添加到您的日期

      doc

      【讨论】:

        【解决方案5】:

        试试 合同日期:clients.contractDate.toJSON(),

        而不是 合同日期:clients.contractDate,

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-09-15
          • 2019-07-25
          • 2020-05-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多