Search code examples
angularangular-reactive-forms

Type 'AbstractControl | null' is not assignable to type 'NgIterable<any> | null | undefined'


my component.ts code is

forms = new FormGroup({
    topics: new FormArray([]),
  });

  addTopic(topic: HTMLInputElement) {
    (this.refForm as FormArray).push(new FormControl(topic.value));
    // topic.value = '';
  }

  get refForm() {
    return this.forms.get('topics');
  }

and .html file has following code.

<form [formGroup]="forms">
  <input
    type="text"
    class="form-control"
    (keyup.enter)="addTopic(topic)"
    #topic
  />
  <ul class="list-group">
    <li *ngFor="let topic of forms.get('topics')">
      class="list-group-item">
      {{ topic.value }}
    </li>
  </ul>
</form>

I tried to find and fix the problem but solutions or answer are not available.


Solution

  • You need to iterate over controls but you're passing an instance of AbstractControl or possible null value to ngFor loop.

    I guess you wanted to pass array of controls in your FormArray.

    You already have a get helper that can be enhanced with correct type:

    get refForm() {
      return this.forms.get('topics') as FormArray;
                                      ^^^^^^^^^^^^
    }
    

    with the above code you can correct your html

    *ngFor="let topic of refForm.controls"