Himansshu Tomar
Himansshu Tomar

Reputation: 23

not able to iterate on FormArray

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);
  }

Upvotes: 2

Views: 1249

Answers (3)

Yong Shun
Yong Shun

Reputation: 51160

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

Upvotes: 0

FunkMonkey33
FunkMonkey33

Reputation: 2258

Just put an *ngIf on your form:

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

It's rendering before your formGroup is done initializing.

Upvotes: 1

N.F.
N.F.

Reputation: 4184

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

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

Upvotes: 2

Related Questions