Currently, I'm referring to the Angular Material example found at https://angular.io/api/forms/FormArrayName
Upon initializing the packageForm formGroup in ngOnInit() and logging it in the console during ngAfterViewInit(), I can see that the translations FormArray is present. However, when trying to access it in the HTML, I encounter an undefined error. Even after using a safe-navigation operator on the formArray, the issue persists with nothing being displayed.
Below is the code snippet from the component.ts file:
ngOnInit() {
this.packageModel = this.activatedRoute.snapshot.data['package'];
if (this.packageModel) {
this.editting = true;
} else {
this.packageModel = new PackageModel(null, true, 1, 0, 0, []);
}
this._setupForm();
}
ngAfterViewInit() {
console.log(this.packageForm)
}
private _setupForm() {
this.packageForm = this.formBuilder.group({
isActive: [this.packageModel.isActive, [Validators.required]],
quantity: [this.packageModel.quantity, [Validators.required]],
minPrice: [this.packageModel.minPrice, [Validators.required]],
maxPrice: [this.packageModel.maxPrice, [Validators.required]],
translations: this.formBuilder.array([
this._createTranslationFormGroup(0),
this._createTranslationFormGroup(1)
])
});
console.log(this.packageForm)
this.packageForm.get('isActive').valueChanges.subscribe(value => {
this.packageModel.isActive = value;
});
}
private _createTranslationFormGroup(index: number) {
return this.formBuilder.group({
name: [this.packageModel.translations[index].name, [Validators.required]],
description: [this.packageModel.translations[index].description, [Validators.required]]
});
}
Here is the corresponding HTML code snippet:
<div *ngIf="packageForm" class="package-form" [formGroup]="packageForm">
<div formArrayName="translations">
<div class="row" *ngFor="let translation of translations.controls; index as i" [formGroupName]="i">
<div class="col-6">
<mat-form-field>
<input type="text" matInput [formControlName]="name" />
</mat-form-field>
</div>
</div>
</div>
</div>
The error message received states: ERROR TypeError: Cannot read property 'controls' of undefined
Please refer to this screenshot for visualization: https://i.sstatic.net/cIoFE.png
Thank you in advance for your assistance!