首页 > 解决方案 > Angular 2 Reactive Forms - How to show the FormArray controls different than input element

问题描述

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.

标签: angularforms

解决方案


如果您只想显示值,请使用“值”。您可以使用

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

但你也可以使用

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

看到 userForm.get('hobbies').value 是一个数组


推荐阅读