0

Getting error on when addAdd() call from html template.

this.personalForm = this.fb.group({
        user: this.fb.group({
            address: this.fb.array([this.addRows()])     
            }),
addRows() {
  return this.fb.group({
    country: ['']});

addAdd() {
  const control:FormArray = this.personalForm.get[`address`] as FormArray;
  control.push(this.addRows());
}

Where i am doing wrong

ERROR TypeError: Cannot read property 'push' of undefined

html code

<button (click)="addAdd()">Add Address</button>
 <div formArrayName="address">
    <div *ngFor="let add of personalForm.controls?.address?.controls; let i=index" [formGroupName]="i">
    <label>Country</label>
  <input type="text" class="form-control"   formControlName="country" 
  placeholder="Country" />
 </div> 
</div>

3 Answers 3

1

In this case control might be null, add a check for null and length.

const control:FormArray = this.personalForm.get[`address`] as FormArray;
if(control && control.length >0){
  control.push(this.addRows());
}
Sign up to request clarification or add additional context in comments.

2 Comments

failed in compilation
its my bad working ! grate thanks, and i want to add into arrays but its just replacing with 1 single array every time i click
1

get is a function, not an object. Also, you must specify full path to your control.

const control:FormArray = this.personalForm.get(['user', 'address']) as FormArray;

or

const control:FormArray = this.personalForm.get('user.address') as FormArray;

1 Comment

This is working ! superb also incrementing FormArray
0

Thanks Marko ! this is working, cool !

addAdd() {
    const control:FormArray = this.personalForm.get('user.address') as FormArray;  
    control.push(this.addRows());  
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.