0

I'm trying to use FormArray with elements other than input element. Most of the examples I've seen uses input element as the dynamically presented objects.

In the component I've added the FormArray.

newHobby: string = null;
employmentForm: FormGroup;

ngOnInit() {
    this.userForm = new FormGroup({
      'hobbies': new FormArray([])
    });
}

onAddHobby() {
    const control = new FormControl(this.newHobby, Validators.required);
    (<FormArray>this.employmentForm.get('hobbies')).push(control);
}

And in the html,

<form [formGroup]="userForm">
    <div class="form-group" formArrayName="hobbies">
        <input type="text" id="new-hobby" class="form-control" [(ngModel)]="newHobby" [ngModelOptions]="{standalone: true}">
        <button class="btn btn-outline-secondary btn-sm mt-3" type="button" (click)="onAddHobby()">Add Hobby</button>
        <ul class="list-group">
          <li class="list-group-item"
            *ngFor="let hobbyControl of userForm.get('hobbies').controls; let i = index"
            [formControlName]="i" [innerHtml]="hobbyControl[i]"></li>
        </ul>
    </div>
</form>

But whenever I'm trying to add a hobby, by clicking the Add Hobby button I'm seeing the following error.

FormArray Error

Can you please point out, where am I doing wrong. Or FormArray does not support controls other than input.

1 Answer 1

1

If you only want to show the value use "value". You can use

  <li class="list-group-item"
    *ngFor="let hobbyControl of userForm.get('hobbies').controls; let i = index"
    [formControlName]="i" [innerHtml]="hobbyControl[i].value"></li>

But you can also use

  <li class="list-group-item"
    *ngFor="let hobbyValue of userForm.get('hobbies').value; let i = index"
    [innerHtml]="hobbyValue"></li>

See that userForm.get('hobbies').value is an array

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. Actually the second option worked. Somehow the [formControlName]="i" is having problem and showing the same error. Here the intention is to show the values, so the second option is quite appropriate.

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.