【问题标题】:angular 4 material show formArrayName with ngFor and ngModelangular 4 材质显示带有 ngFor 和 ngModel 的 formArrayName
【发布时间】:2018-06-03 08:22:19
【问题描述】:

我正在尝试使用 Angular 4 react 表单显示一组电子邮件,并从我的输入中绑定一个数组,所以在组件中我写了这个:

<li>
 <h4>Telephone</h4>
 <div class="lists" formArrayName="telephones">
  <mat-form-field *ngFor="let telephone of userData.telephones; let i = index">
   <input matInput [(ngModel)]="telephone">
  </mat-form-field>
 </div>
</li>

我需要显示一个电话号码数组,并且我想使用 ngModel 使其字段可编辑。

我尝试了很多东西: 具有 [formGroupName]="index" 和 formControlName="" 的 formArrayName 解决方案,但它不起作用。 也是一个带有 ngFor 解决方案的 ngModel,它需要一个唯一的名称。

【问题讨论】:

    标签: angular ngfor angular4-forms ngmodel formarray


    【解决方案1】:

    不要将响应式表单与模板驱动混用。选择其中之一。由于您正在使用数组,因此请使用反应形式。似乎您的数组是原始类型,这意味着您可以直接分配值而无需循环数组。

    constructor(private fb: FormBuilder) {
      this.myForm = this.fb.group({
        telephones: this.fb.array(this.userData.telephones)
      });
      // if receiving data at a later point, use below instead
      //this.myForm.setControl('telephones', this.fb.array(this.userData.telephones))
    }
    

    然后在你的模板中迭代你的表单数组(这里没有角材料):

    <div formArrayName="telephones">
      <div *ngFor="let tel of myForm.controls.telephones.controls; let i = index">
        <input [formControlName]="i" />
      </div>
    </div>
    

    StackBlitz

    【讨论】:

    • 非常感谢!!它的工作!是的,我将响应式表单与模板驱动混合在一起。我仍然在学习!!还有一件事,我怎样才能直接设置反应形式的值?再次感谢!
    • 你是什么意思以反应形式直接设置值?如果您的意思是像为数组设置值,这就是我所做的,否则您也可以为任何表单控件设置值:stackblitz.com/edit/angular-1mavrl?file=app/app.component.ts
    • 如果有兴趣尝试在模板驱动的表单中使用 ngFor,请点击此处:stackoverflow.com/questions/39615780/…
    猜你喜欢
    • 2017-10-13
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 2018-04-25
    • 2018-11-11
    • 2021-09-18
    • 1970-01-01
    • 2018-04-24
    相关资源
    最近更新 更多