Angular 5将日期绑定到字段(反应形式)

时间:2018-04-23 08:16:40

标签: javascript angular typescript

输入类型日期有问题。我想绑定组件中的数据。这是我的领域:

<div class="col-md-6">
    <label for="dateOfReport">Data zgłoszenia błędu:</label>
    <input type="date" formControlName="dateOfReport" id="dateOfReport" class="form-control" [value]="report.dateOfReport | date:'dd.MM.yyyy'"> {{report.dateOfReport | date:'dd.MM.yyyy'}}
  </div>

以下是变量dateOfReport的外观:

new Date().toJSON().slice(0, 10)

我失败的地方? {{..}}显示了良好的约会,但我的字段不会将其视为默认日期。

3 个答案:

答案 0 :(得分:2)

使用Reactive Forms时,不应将数据直接绑定到控件,而应使用FormGroup的setValue()或patchValue()。

答案 1 :(得分:2)

    <div class="col-md-6">
        <label for="dateOfReport">Data zgłoszenia błędu:</label>
        <input type="date" formControlName="dateOfReport" id="dateOfReport" class="form-control" [value]="report.dateOfReport | date:'dd.MM.yyyy'"> {{report.dateOfReport | date:'dd.MM.yyyy'}}
      </div>

In your TS file use ur formGroup Name and access the element. For Example if you have FormGroup name as myForm and you have the formcontrolname in it as dateOfReport you can set values to it like this.

    `this.myForm.patchValue({
    dateOfReport:'YOUR TIME VARIABLE HER'
    });`

You can either use setValue or patchValue in this case. Not that setValue wont fail silently. But patchValue will fail silent. It is recommended to use patchValue therefore

答案 2 :(得分:0)

在使用响应式表单创建表单时,我找到了将日期绑定到输入的答案。

我使用的是 Angular 11。

这是 HTML

<div class="form-group">
  <label for="dateOfReport">Report Date</label>
  <input type="date" class="form-control" name="dateOfReport" id="dateOfReport" formControlName="dateOfReport" />
</div>

这是我的角度分量

// ...other imports
import { formatDate } from "@angular/common";

// ...

//... creating the form
this.form = this.formBuilder.group({
  dateOfReport: [formatDate(new Date(), "yyyy-MM-dd", "en"), [Validators.required]],
  // other form fields
});