【问题标题】:Why it is passing index instead of FormControl object into FormControlNameDirective?为什么将索引而不是 FormControl 对象传递给 FormControlNameDirective?
【发布时间】:2018-01-16 04:59:09
【问题描述】:

参考:https://angular.io/docs/ts/latest/api/forms/index/FormArrayName-directive.html

HTML:

<form  [formGroup]="form" (ngSubmit)="onSubmit()"> 
  <div formArrayName="cities">    
    <div *ngFor="let city of cities.controls; index as i">
        <input [formControlName]="i" placeholder="City">
   </div> 
 </div> 
 <button>Submit</button> 
</form>

为什么将 i 传递给 formControlName 而不是实际的表单控件 city

【问题讨论】:

  • 我很确定这是因为您没有正确获取索引。你需要这样写:&lt;div *ngFor="let city of cities.controls; let i = index"&gt;
  • 因为该指令接受控件的名称而不是值

标签: angular angular-directive angular-forms


【解决方案1】:

因为此代码正在使用名为 cities 的表单数组:

  <div formArrayName="cities">    
    <div *ngFor="let city of cities.controls; index as i">
        <input [formControlName]="i" placeholder="City">
   </div> 
 </div> 

数组中控件的名称由它们的索引号定义: 城市[0];城市[1];城市[2];等等

city 变量是对控件的引用,而不是它的“名称”,对于数组来说,它是索引。

有意义吗?

【讨论】:

  • 是的,每个 formControl 都需要一个唯一的名称才能被引用。索引 i 是一个完美的候选人。
猜你喜欢
  • 2013-05-18
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 2014-03-05
  • 1970-01-01
  • 2020-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多