【问题标题】:Angular2 bind array with ngForAngular2 使用 ngFor 绑定数组
【发布时间】:2016-08-10 06:33:06
【问题描述】:

我正在使用 angular2,在我的表单中,我通常创建一个模型类并将我的对象与表单绑定,然后通过 this.myObject 访问。

<div class="form-group ">
 <label class="col-md-3 control-label">Label</label>
 <div class="col-md-6">
  <input type="text" class="form-control" [(ngModel)]="diplome.label" name="label">
 </div>
</div>

稍后获取我的数据

private diplome = new Diplome();
let myData = this.diplome;

当我使用*ngFor 显示数据数组时,我现在处于一个位置,我希望在单击提交时将所有这些数据作为特定类的数组。

...
<tr *ngFor="let inscription of inscriptions">
 <td>
   <span *ngIf="inscription._etudiant">{{ inscription._etudiant.label }}</span>
 </td>
 <td>
  <div class="form-group ">
    <div class="col-md-6">
     <input type="number" class="form-control" name="note">
    </div>
  </div>
 </td>
</tr>
...

我希望能够在每次迭代中使用绑定将数据插入到输入中的铭文对象。

【问题讨论】:

  • 你想从哪里得到它?
  • 在我的 component.ts 中触发提交点击按钮后。

标签: angular


【解决方案1】:

您可以尝试使用FormArray 类将您的输入绑定到一个数组。我在下面为您写了一个快速演示。最好使用 FormBuilder 来设置表单,因为您可以将 Validators 绑定到您的 FormControls,并且您可以简单地使用 FormGroup.value 获取模型对象。

import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'ExampleForm',
  template: `<form [formGroup]="formGroup">
               <div formArrayName="formArray">
                 <div *ngFor="let control of formGroup.controls.formArray.controls; let i=index">
                   <input type="text" formControlName="{{i}}">
                 </div>
               </div>
               <button (click)="addInput()">Add Input</button>
             </form>
             <pre>{{formGroup.value | json}}</pre> `
})
export class ExampleForm {
  private formGroup: FormGroup;

  constructor(private fb: FormBuilder) {
    this.formGroup = this.fb.group({
      formArray: this.fb.array([
        this.fb.control('')
      ])
    });
  }

  addInput() {
    this.formGroup.controls.formArray.push(this.fb.control(''));
  }
}

【讨论】:

  • 当我这样做时,打字稿编译器会显示Property formArray does not exist on type ...。这真的对你有用吗?我可以运行代码,当我控制台记录this.formGroup 时,我得到包含formArray 的对象,因为这在运行时是正确的。如何解决?
猜你喜欢
  • 2017-05-08
  • 1970-01-01
  • 2018-04-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多