When using a reactive form to display information, I encountered an issue where one field in the form group was not rendering the value until the page was refreshed. Here is a simplified version of the code:
.ts file
private getPhaseParId(id: number) {
this.phasesService.getPhaseParId(id)
.subscribe(
(phase: Phase) => {
if (phase) {
this.maPhase = phase;
console.log("before updatePhaseFormulaire()",this.phaseFormulaire.get('predecesseur').value);
this.updatePhaseFormulaire();
console.log("after updatePhaseFormulaire()",this.phaseFormulaire.get('predecesseur').value);
} else {
// else block treatment
}
},
erreur => {
// error block treatment
})
}
private updatePhaseFormulaire(): void {
this.phaseFormulaire.patchValue({
id: this.maPhase.id,
nom: this.maPhase.nom,
predecesseur: this.maPhase?.predecesseur
})
}
and .html snippet
<form [formGroup]="phaseFormulaire" class="needs-validation" novalidate>
<div class="form-row">
<select class="form-input heightFixed" id="predecesseur"
formControlName="predecesseur"
title="{{ 'phase.formulaire.predecesseur.input.infobulle' | translate}}">
<option [ngValue]="null||undefined" *ngIf="phaseListe && phaseListe.length > 0">
{{ 'phase.formulaire.predecesseur.placeholder.libelle' | translate}}
</option>
<option [ngValue]="null||undefined" *ngIf="!phaseListe || phaseListe.length === 0">
{{ 'phase.formulaire.predecesseur.aucunPredecesseur.libelle' | translate}}
</option>
<option [ngValue]="predecesseur" *ngFor="let predecesseur of predecesseursListe | orderBy:'nom'" [attr.selected]="predecesseur.id == this.maPhase?.predecesseur?.id ? true : null">
{{predecesseur.nom}}
</option>
</select>
</div>
</form>
Despite setting up the code as shown above, the predecesseur formControlName does not display anything on the page initially. However, with console.log before and after the update function, the output shows:
- before updatePhaseFormulaire:
Phase {}
- after updatePhaseFormulaire:
{id: 1, nom: 'Admissibilité',statutOk: 'Accepté', statutKo: 'Refusé', …}
I have attempted to use ngAfterViewInit()
but it did not resolve the issue. Does anyone have any ideas on how to fix this bug?