Reputation: 23
I have an angular mattimepicker. I am using it in a reactive form. I am finding it difficult to patch the value to the edit form
<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" This is the value I am trying to patch it to the above formfield Kindly help if you guys know
Stackblitz: https://stackblitz.com/edit/mat-timepicker-current-time-3ns5r1?file=src%2Fapp%2Fapp.component.html
Upvotes: 0
Views: 1771
Reputation: 53
Take any random date and set its value to time formControlName Your ts file will look like:-
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 });
}
}
Upvotes: 0
Reputation: 1152
Set this on your ngOnInit()
your matdatepicker will have a default value of 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);
}
see stackblitz: https://stackblitz.com/edit/mat-timepicker-current-time-glnur8
Upvotes: 0
Reputation: 972
Please check if this is what you want. You will have to use 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
Upvotes: 0