I have a Angular 7 app where I am implementing some reactive forms.
The initialization of my reactive form looks like this:
private initFormConfig() {
return this.formBuilder.group({
modeTransfert: [''],
modeChiffrement: [''],
});
}
Within my form, there are various inputs and mat-select elements:
<div class="form-inline form-group">
<label class="col-md-2 justify-content-start">Target URL</label>
<input id="urlCible"
type="text"
maxlength="200"
ngDefaultControl
formControlName="urlCible"
class="col-md-6 form-control"/>
</div>
<div class="form-inline form-group">
<label class="col-md-2 justify-content-start">Transfer Mode</label>
<mat-form-field class="col-md-3" color="warn">
<mat-select placeholder="Select transfer mode"
id="modesTransfert"
[(value)]="selectedModeTransfert"
ngDefaultControl
formControlName="modeTransfert">
<mat-option *ngFor="let modeTr of modeTransfertData"
[value]="modeTr.value">
{{modeTr.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
</div>
I am facing challenges in setting the default value for the select input. The main issues are:
The use of ngModel with ngFormControl (reactive form) is deprecated in Angular 7
Trying to patch its value like this leads to errors:
this.addPefForm.patchValue({'modeTransfert': this.modeTransfertData[0].value});
This cannot be done initially in the onInit or AfterViewChecked hooks due to resulting error:
ParametragePefAdministrationFormComponent.html:107 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'mat-selected: false'. Current value: 'mat-selected: true'.
at viewDebugError (core.js:20342)
at expressionChangedAfterItHasBeenCheckedError (core.js:20330)
at checkBindingNoChanges (core.js:20432)
at checkNoChangesNodeInline (core.js:23305)
at checkNoChangesNode (core.js:23292)
at debugCheckNoChangesNode (core.js:23896)
at debugCheckRenderNodeFn (core.js:23850)
at Object.eval [as updateRenderer] (ParametragePefAdministrationFormComponent.html:107)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:23839)
at checkNoChangesView (core.js:23193)
- I also attempted to bind it using
[(value)]="selectedModeTransfert"
However, none of these solutions worked.
Any suggestions?