I met a problem where I tried to patchValue for one of control in a formgroup. And it never success. I use Angular Material DatePicker with moment.js
Here is the HTML:
<form novalid [formGroup]="desktopSearchForm">
<div class="row-content" *ngIf="dateRange">
<mat-form-field class="desktop-input">
<input matInput [min]="minDate" [max]="maxDate" [matDatepicker]="mobileFromDate" placeholder="From" formControlName="startDate" (focusout)="dateParse(desktopSearchForm.get('startDate'))" />
<mat-datepicker-toggle matSuffix [for]="mobileFromDate"></mat-datepicker-toggle>
<mat-datepicker #mobileFromDate></mat-datepicker>
</mat-form-field>
</div>
</form>
Here is the function I call in (focusout)
this.desktopSearchForm = this.fb.group({
classID: [''],
startDate: [''], //This is the one I want to patch
endDate: [''],
transactionTypeID:['']
})
dateParse(control) {
if (control.value) {
//control.value is a Moment.js Date object
let group = <FormGroup>control.parent;
let TheKey;
Object.keys(group.controls).forEach(key => {
let childControl = group.get(key);
if (childControl === control) { // I found the Control I want to patch
TheKey = key;
}
})
group.patchValue({TheKey:control.value}) //I patch it here.
}
this function is for auto assign the correct date format back to the input field (image there are many datepickers with different name such as startDate,endDate etc). e.g I type 25111988 into the input box,while I focus out, the input value changes to '25/11/1988'. But the problem is the control.value never patch to the key which is correctly show 'startDate'.
But If I change it to this and it works:
group.patchValue({startDate : control.value })
Also here is an another problem is:
if I put group.patchValue({startDate : control.value }) into :
Object.keys(group.controls).forEach(key => {
let childControl = group.get(key);
if (childControl === control) {
group.patchValue({startDate : control.value })
}
})
Then it does not work.that's why I put this patch function outside of the forEach.
Need Help. Many Thanks.