Home > OS >  not able to iterate on FormArray
not able to iterate on FormArray

Time:10-08

am using approach of -- formGroup -- -- FormControl -- , -- FormArray -- ----------------- -- FormControlList --

I have also tried FormArray within nested Form Group

But am not able to iterate Form Array, Please let me know if approach is right.

HTML Error--: Object possibly 'null' - controls

CODE -

HTML --
<form [formGroup]="abcForm">
    <section>
<div formArrayName="title">
<ul>
  <li *ngFor="let control of abcForm.get('title').controls; let i= index;">
       {{i}}
  </li>
</ul>
</div>
</form>

/////////////////////

TS --

titles: any = [
    {
      name: "one",
      value: "one",
      selected: false
    },
    {
      name: "two",
      value: "two",
      selected: true
    },
    {
      name: "three",
      value: "three",
      selected: true
    },
  ];

constructor(private fb: FormBuilder)
this.abcForm = this.fb.group({
      one: ['',Validators.required],
      title:
        this.buildTitleControls()
      ,
    });

buildTitleControls() {
    const arr = this.titles.map((val : any) => {
      return this.fb.control('');
    });
    return this.fb.array(arr);
  }

CodePudding user response:

You have to add ? to abcForm.get('title').

<li *ngFor="let control of abcForm.get('title')?.controls; let i= index;">

CodePudding user response:

Just put an *ngIf on your form:

<form [formGroup]="abcForm" *ngIf="abcForm">

It's rendering before your formGroup is done initializing.

CodePudding user response:

You can write a getter for title to retrieve controls as FormArray.

And for HTML use title.controls.

get title(): FormArray {
  return this.abcForm.controls['title'] as FormArray;
}
<li *ngFor="let control of title.controls; let i = index">
  {{ i }}
</li>

Sample Solution on StackBlitz

  • Related