Why do i get an error saying error TS2339: Property 'controls' does not exist on type 'AbstractControl'
Solution 1:
This was a tough one to solve thanks @bjdose.
After reviewing many solutions I have now put together some code that works for anyone else having this problem.
Template
<form name="mainForm" [formGroup]="mainForm">
<div formArrayName="phoneNumbers">
<div *ngFor="let phoneNumber of getPhoneNumbers(); let i = index">
<div [formGroupName]="i">
<mat-form-field>
<mat-label>Label</mat-label>
<input matInput placeholder="Label" name="label"
formControlName="label"/>
</mat-form-field>
<mat-form-field>
<mat-label>Number</mat-label>
<input matInput placeholder="Number" name="number"
formControlName="number"/>
</mat-form-field>
<button mat-raised-button type="button"
(click)="addPhoneNumber()">Add</button>
<button mat-raised-button type="button"
(click)="removePhoneNumber(i)">Remove</button>
</div>
</div>
</div>
</form>
TS CODE
import { FormBuilder, FormGroup, FormArray, FormControl } from "@angular/forms";
import { ActivatedRoute, Router } from "@angular/router";
@Component({
selector: "fw-person",
templateUrl: "./person.component.html",
styleUrls: ["./person.component.scss"],
})
export class PersonComponent implements OnInit {
id: string;
mainForm: FormGroup;
entity: Person;
constructor(
private _formBuilder: FormBuilder,
) {
this.entity = new Person();
}
ngOnInit(): void {
this.id = this._activatedRoute.snapshot.params["id"];
this.country = _.find(this.countries, {
id: this._translateService.currentLang
});
if (this.id !== "new") {
this._dataService.getByKey(this.id).subscribe(entity => {
this.entity = new Person(entity);
this.updateFormFields(entity);
});
} else {
this.pageType = "new";
this.entity = new Person();
}
this.mainForm = this.createPersonForm();
}
createPersonForm(): FormGroup {
return this._formBuilder.group({
id: [this.entity.id],
code: [this.entity.code],
firstName: [this.entity.firstName],
familyName: [this.entity.familyName],
handle: [this.entity.handle],
companyId: [this.entity.companyId],
phoneNumbers: this._formBuilder.array([this.newPhoneNumber()]),
tags: [this.entity.tags],
images: this._formBuilder.array([this.entity.images]),
active: [this.entity.active]
});
}
updateFormFields(entity): void {
Object.keys(this.mainForm.controls).forEach(key => {
this.mainForm.controls[key].patchValue(entity[key]);
});
}
newPhoneNumber(): FormGroup {
return this._formBuilder.group({
label: "",
number: ""
});
}
addPhoneNumber() {
(this.mainForm.get("phoneNumbers") as FormArray).push(
this.newPhoneNumber()
);
}
removePhoneNumber(i: number) {
(this.mainForm.get("phoneNumbers") as FormArray).removeAt(i);
}
getPhoneNumbers(): any {
return (this.mainForm.get("phoneNumbers") as FormArray).controls;
}
}