gpt4 book ai didi

javascript - 带有 [ngmodel] 的 Angular Material 2 日期选择器

转载 作者:数据小太阳 更新时间:2023-10-29 03:49:03 26 4
gpt4 key购买 nike

我正在尝试将我的日期属性绑定(bind)到 mat-datepicker 的输入,作为响应式(Reactive)表单组的一部分。我的所有方法都不起作用,因为我的提交按钮设置为禁用,除非表单有效:

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

组件.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(),
});

无效的方法:

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

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

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

我只需要让 [ngModel] 正常工作,以便 Reactive Form 读取它。

非常感谢帮助!

编辑这是我的表单组:

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>

这是我现在得到的错误:

Error: Cannot find control with unspecified name attribute

最佳答案

Angular 提供了两种使用表单的方式:template-drivenreactive .您将这两者混在一起,而您应该选择要使用的那一个。文档可以指导您做出这个选择。

如果你选择模板驱动,你可以使用[(ngModel)](就像你的方法1)。

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

startDate = new Date();

选择响应式(Reactive),您可以在 Controller 中使用 [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],否则它会给您带来意想不到的结果。

关于javascript - 带有 [ngmodel] 的 Angular Material 2 日期选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48053317/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com