首页 文章

Angular material 2 datepicker with [ngmodel]

提问于
浏览
2

我试图将我的日期属性绑定到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" 添加到输入字段

  • 使用以下值预加载formControl: startingDate: new FormControl(this.startDate),

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

  • [value]="startDate" 添加到输入字段:显示日期但未被活动表单读取,这意味着我的提交按钮保持禁用状态,因为表单无效 . 为了使其有效,我必须手动设置日期(键入或使用日期选择器)

  • 从输入字段中删除 [matDatepicker]="datepicker1" 时添加 [ngModel]="startDate" :显示日期但删除了对datepicker的访问权限 .

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

非常感谢!

EDIT 这是我的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>

这是我现在得到的错误:

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

2 回答

  • 4

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

    如果选择模板驱动,可以使用 [(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
    

    如果你不做't know what you',切勿使用 [value] ,否则会给你意想不到的结果 .

  • 0

    解决了,谢谢@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>
    

相关问题