我试图将我的日期属性绑定到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>
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(),
});
无效的方法:
[(ngModel)]="startDate"
添加到输入字段[ngModel]="startDate"
添加到输入字段startingDate: new FormControl(this.startDate),
预加载formControl部分但不令人满意的方法:
[value]="startDate"
添加到输入字段:显示日期但未被活动表单读取,这意味着我的提交按钮保持禁用状态,因为表单无效。为了使其有效,我必须手动设置日期(键入或使用日期选择器)[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(),
});
这是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>
这是我现在得到的错误:
错误:找不到具有未指定名称属性的控件
Angular提供了两种使用形式的方法:template-driven或reactive。你把它们混合起来,而你应该选择你想要使用的那个。文档可以指导您进行此选择。
如果你选择模板驱动,你可以使用[(ngModel)]
(就像你的方法1)。
<input matInput [matDatepicker]="datepicker1" placeholder="Start Date" [(ngModel)]="startDate" required>
startDate = new Date();
选择反应,你可以在控制器中使用[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
如果你不知道你在做什么,或者它会给你意想不到的结果,切勿使用[value]
。
解决了,谢谢@Manduro帮助我解决这个问题
this.startDate
是一个字符串,而Datepicker只翻译日期。
最终,这是我为使其工作而添加的内容。
startingDate: new FormControl(moment(this.startDate).format())
HTML:
<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>