Cannot read property 'controls' of undefined
15,658
Solution 1
You fetch data async and it is not yet available when Angular first renders the view. You can guard agains this error using the safe-navigation operator:
<div *ngFor="let laboratoire of laboFormGeneral?.controls?.laboratoire?.controls; let i=index">
Solution 2
try to check laboFormGeneral.controls.laboratoire.controls
in *ngIf
, if it's not undefined
then iterate on your controls
:
<form [formGroup]="laboFormGeneral" novalidate>
<div *ngIf="laboFormGeneral && laboFormGeneral.controls && laboFormGeneral.controls.laboratoire && laboFormGeneral.controls.laboratoire.controls" formArrayName="laboratoire">
<div *ngFor="let laboratoire of laboFormGeneral.controls.laboratoire.controls; let i=index">
<div class="textAlign" [formGroupName]="i">
<ion-input type="text" formControlName="name"></ion-input>
<ion-input type="text" formControlName="mail"></ion-input>
</div>
</div>
</div>
</form>
Author by
Hamdy
Updated on June 14, 2022Comments
-
Hamdy almost 2 years
I want to display data on a formArray on Angular 4. On the constructor, I called the service.
this.LaboratoireListServiceProvider.getLaboratoires().subscribe( data => { this.listLabo = data; this.initFormGeneral(); for (let i = 0; i < data.length; i++) { let element=this.formBuilder.group({ name: [data[i].name,], mail: [data[i].mail,], checked: [], }); this.Labo.push(element); } console.log(this.laboFormGeneral.get('laboratoire').value); }
);
In a separate method, I wrote this code:
initFormGeneral() { return this.laboFormGeneral = this.formBuilder.group({ laboratoire: this.formBuilder.array([]) }); }
When I comfort the lab value, I get the write values without any problem.
When I add the html block, I get the error
"Unable to read the 'properties' of 'undefined'"
<form [formGroup]="laboFormGeneral" novalidate> <div formArrayName="laboratoire"> <div *ngFor="let laboratoire of laboFormGeneral.controls.laboratoire.controls; let i=index"> <div class="textAlign" [formGroupName]="i"> <ion-input type="text" formControlName="name"></ion-input> <ion-input type="text" formControlName="mail"></ion-input> </div> </div> </div> </form>
How I can resolve this problem ?
-
Mohamed Ali RACHID over 6 yearsare you using
.controls
in other part of code ? -
Hamdy over 6 yearsNo I am not using .controls inside the code
-
-
Hamdy over 6 yearsI call
this.initFormGeneral();
inside the` ngOnInit()` .The problem goes away. -
Günter Zöchbauer over 6 yearsYou get the error because the form is not initialized, not because you access the controls before they are initialized as I assumed.
-
Mahesh about 5 yearsagree with @GünterZöchbauer. Your form is not getting initialized before your async operation is completed. Due to this, your HTML side will throw an error. Make sure you initialize your form with default value and then make an async call to set form data.