Angular material 2 datepicker with [ngmodel]

shu*_*kar 9 javascript forms datepicker material-design angular

我试图将我的日期属性绑定到mat-datepicker的输入作为反应形式组的一部分.我的所有方法都不起作用,因为我的提交按钮被设置为禁用,除非表单有效:

<mat-form-field fxFlex>
  <input matInput [matDatepicker]="datepicker1" placeholder="Start Date" formControlName="startingDate" required>
  <mat-datepicker-toggle matSuffix [for]="datepicker1"></mat-datepicker-toggle>
  <mat-datepicker touchUi="true" #datepicker1></mat-datepicker>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)

Component.ts:

start: Date.now()
startDate: "1/1/2018"
this.ShiftForm = new FormGroup({
  startingDate: new FormControl(this.startDate),
  startTime: new FormControl(),
  endingDate: new FormControl(this.endDate),
  endTime: new FormControl(),
});
Run Code Online (Sandbox Code Playgroud)

无效的方法:

  1. 添加[(ngModel)]="startDate"到输入字段
  2. 添加[ngModel]="startDate"到输入字段
  3. 使用值预加载formControl: startingDate: new FormControl(this.startDate),

部分但不令人满意的方法:

  1. 添加[value]="startDate"到输入字段:显示日期但未被活动表单读取,这意味着我的提交按钮保持禁用状态,因为表单无效.为了使其有效,我必须手动设置日期(键入或使用日期选择器)
  2. 从输入字段中[ngModel]="startDate"删除时添加[matDatepicker]="datepicker1":显示日期但删除了对datepicker的访问权限.

我只需要[ngModel]就可以正常工作,以便Reactive Form读取它.

非常感谢!

编辑 这是我的formGroup:

this.ShiftForm = new FormGroup({
  startingDate: new FormControl(this.startDate),
  startTime: new FormControl(),
  endingDate: new FormControl(this.endDate),
  endTime: new FormControl(),
});
Run Code Online (Sandbox Code Playgroud)

这是HTML:

<form [formGroup]="ShiftForm" fxLayout="column" fxLayoutAlign="center stretch">
<mat-form-field fxFlex>
  <input matInput [matDatepicker]="datepicker1" placeholder="Start Date" [formControlName]="startingDate" required>
  <mat-datepicker-toggle matSuffix [for]="datepicker1"></mat-datepicker-toggle>
  <mat-datepicker touchUi="true" #datepicker1></mat-datepicker>
</mat-form-field>
..
..
..
</form>
Run Code Online (Sandbox Code Playgroud)

这是我现在得到的错误:

错误:找不到具有未指定名称属性的控件

Man*_*uro 13

Angular提供了两种使用表单的方式:模板驱动反应.你把它们混合起来,而你应该选择你想要使用的那个.文档可以指导您进行此选择.

如果您选择模板驱动,您可以使用[(ngModel)](如您的方法1).

<input matInput [matDatepicker]="datepicker1" placeholder="Start Date" [(ngModel)]="startDate" required>

startDate = new Date();
Run Code Online (Sandbox Code Playgroud)

选择的反应,你可以使用[formControl]一个FormControl在你的控制器(如您的方法3).

<input matInput [matDatepicker]="datepicker1" placeholder="Start Date" [formControl]="startDate">

startDate = new FormControl(new Date(), Validators.Required);
// Use `startDate.value` to get the value of the control
Run Code Online (Sandbox Code Playgroud)

[value]如果您不知道自己在做什么,或者它会给您带来意想不到的结果,请不要使用.