angular 反应形式的补丁 mattimepicker

patch mattimepicker in angular reactive form

我有一个 angular mattimepicker。我以反应形式使用它。我发现很难将值修补到编辑表单

    <h1>Reactive Form</h1>
<form [formGroup]="form">
    <mat-form-field class="example-full-width">
        <mat-label>Time</mat-label>
        <input formControlName="time" matTimepicker>
  </mat-form-field>
</form>

"1:32 PM" 这是我试图将其修补到上面的表单域的值 知道的请帮忙

Stackblitz:https://stackblitz.com/edit/mat-timepicker-current-time-3ns5r1?file=src%2Fapp%2Fapp.component.html

在您的 ngOnInit() 上进行设置,您的 matdatepicker 将具有默认值 1:32

newTime = {
    hour: null,
    min: null,
    timeclock: null
}
assume_backendTime = '1:32 AM';

ngOnInit() {
  /* extracting the time only | 1:32 PM = 1:32 */
  let timeOnly = this.assume_backendTime.replace(/[0-9]/g, '');
  /* extracting the AM/PM | 1:32 PM = PM */
  this.newTime.timeclock = this.assume_backendTime.replace(/[^a-z]/gi, '');
  /* separating the hour:minute separated by : into array  */
  let timeArry = this.assume_backendTime.split(/[ :]+/);
  this.newTime.hour = timeArry[0];
  this.newTime.min = timeArry[1];
  console.log(this.newTime)
  let patchTime = new Date()
  patchTime.setHours(this.newTime.hour, this.newTime.min);
  this.form.controls['time'].patchValue(patchTime);
}

查看 stackblitz:https://stackblitz.com/edit/mat-timepicker-current-time-glnur8

请检查这是否是您想要的。您将不得不使用 moment

 ngOnInit() {
    const input = '1:32AM';
    const momentDate = moment(input, ["h:mm A"]).toDate();
    this.form.patchValue({ time: momentDate });
  }

https://stackblitz.com/edit/mat-timepicker-current-time-jt6zwd?file=src/app/app.component.ts

取任何随机日期并将其值设置为时间 formControlName 您的 ts 文件将如下所示:-

export class AppComponent implements OnInit{
  form = new FormGroup({
    time: new FormControl()
  });
  ngOnInit() {
   const event = new Date('May 30,  01:32:30');
    this.form.patchValue({ time:event });
  }
}