如何使用 patchValue 以角度反应形式设置日期

Shi*_*aay 6 bootstrap-datepicker angular angular7

我正在尝试随时间设置 datepicker 控件的值。无法完成

尝试转换为所需格式

应用程序组件.html

<input id="requestdate" type="date" class="form-control" formControlName="requestdate" 

Run Code Online (Sandbox Code Playgroud)

app.component.ts

ngOnInit() {

this.loginForm = this.formBuilder.group({ 
                    requestdate : ['']
                  })

let date = new Date()
date = date.toLocaleDateString().substring(0,10)

this.loginForm.get('requestdate').patchValue(date)


}
Run Code Online (Sandbox Code Playgroud)

无法看到转换后的日期

Sid*_*era 12

您在重新分配date变量时似乎使用了错误的语法。由于它被初始化为 a Date,它不会接受您提供它的格式的字符串。您必须使用该YYYY-MM-DD格式。

尝试这个:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  loginForm: FormGroup;

  constructor(
    private formBuilder: FormBuilder
  ) { }

  ngOnInit() {
    this.loginForm = this.formBuilder.group({
      requestdate: ['']
    })
    this.loginForm.get('requestdate').patchValue(this.formatDate(new Date()));
  }

  private formatDate(date) {
    const d = new Date(date);
    let month = '' + (d.getMonth() + 1);
    let day = '' + d.getDate();
    const year = d.getFullYear();
    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;
    return [year, month, day].join('-');
  }
}
Run Code Online (Sandbox Code Playgroud)

不要忘记将input字段包裹在属性设置为的form标签周围:formGrouploginForm

<form [formGroup]="loginForm">
  <input
    id="requestdate" 
    type="date" 
    class="form-control" 
    formControlName="requestdate" />
</form>
Run Code Online (Sandbox Code Playgroud)

这是供您参考的工作示例 StackBlitz