Property 'controls' does not exist on type 'AbstractControl' Angular 4

Munna Babu picture Munna Babu · Oct 25, 2017 · Viewed 58.6k times · Source

I am trying a nested reactive form in Angular 4. It is working fine but when I try to build AOT it's throwing the error

'controls' does not exist on type 'AbstractControl'

I googled and tried few things but no luck. Could anyone tell me how to fix this issue?

<div [formGroup]="myForm">
    <div formArrayName="addresses">
        <div *ngFor="let address of myForm.get('addresses').controls; let i=index" 
                    class="panel panel-default">
            <span *ngIf="myForm.get('addresses').length > 1"
                    (click)="removeAddress(i)">Remove</span>
            <div [formGroupName]="i">
                <mat-form-field>
                    <input matInput formControlName="city" placeholder="city" value="">
                </mat-form-field>
            </div>

        </div>
    </div>
    <a (click)="addAddress()" style="cursor: default"> Add +</a>
</div>

typescript code below

constructor(private _fb: FormBuilder) {     
}

ngOnInit() {
    this.myForm = this._fb.group({
        addresses: this._fb.array([
            this.initAddress(),
        ])
    });
}
initAddress() {
    return this._fb.group({
        city: ['']
    });
}
addAddress() {
    const control = <FormArray>this.myForm.get('addresses');
    control.push(this.initAddress());
}
removeAddress(i: number) {
    const control = <FormArray>this.myForm.get('addresses');
    control.removeAt(i);
}

Answer

Munna Babu picture Munna Babu · Oct 25, 2017

Based on @Günter Zöchbauer comments , first i changed

myForm.controls['addresses'] to myForm.get('addresses') in both html and typescript

and then based on @yuruzi comment

changed myForm.get('addresses').controls to myForm.get('addresses')['controls']

Its working fine now. Thanks @gunter & yuruzi