ngModel未绑定到ngFor select标签内的选项

时间:2019-04-16 01:10:31

标签: html angular

<form>
 <table>
        <tr *ngFor="let p of ArrayObject">
          <td>
            <div>
             <select class="form-control input-sm" [(ngModel)]="p.tag" 
name="tag" #required>
               <option ngValue="YES">YES</option>
               <option ngValue="NO" >NO</option>
             </select>
           </div>
         </td>
        </tr>
      </table>
</form>

我使用ngFor在表单内设置了一个多选标签,它在没有表单标签的情况下仍然可以工作,但是在表单标签内似乎值设置不正确。

1 个答案:

答案 0 :(得分:0)

您需要在ngValue上添加方括号,以将其标识为binding目标属性。它应该看起来像这样[ngValue]

<form>
  <table>
    <tr *ngFor="let p of ArrayObject; let index = index; trackBy:trackByIndex;">
      <td>
        <div>
          <select class="form-control input-sm" [(ngModel)]="p.tag[index]" name="tag{{index}}" #required>
            <option [ngValue]="YES">YES</option>
            <option [ngValue]="NO">NO</option>
          </select>
        </div>
      </td>
    </tr>
  </table>
</form>

在component.ts上,您需要定义trackByIndex方法:

// initialise with the following values to test if it is working
p = {
  tag: ['YES', 'YES', 'NO'] 
};

trackByIndex(index: number, obj: any) {
  return index;
}