[英]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 });
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.