角反应形式的补丁 mattimepicker

时间:2021-05-15 05:26:59

标签: javascript angular angular-material angular5 angular8

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

kCLLocationAccuracyBest

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

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

3 个答案:

答案 0 :(得分:0)

在您的 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);
}

见堆栈闪电战:https://stackblitz.com/edit/mat-timepicker-current-time-glnur8

答案 1 :(得分:0)

请检查这是否是您想要的。您将不得不使用 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

答案 2 :(得分:0)

取任何随机日期并将其值设置为时间 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 });
  }
}