【问题标题】:Checkbox not applying check on load when using *ngFor in Angular 2在 Angular 2 中使用 *ngFor 时复选框未应用负载检查
【发布时间】:2017-05-14 01:58:53
【问题描述】:

我有一个使用*ngFor 构建的复选框的动态列表。每当我手动选中这些框时,模型都会更新得很好,但是如果模型预设有一个选中的框,则加载时不会选中该框。

<form action="demo_form.asp" method="get">
  <div *ngFor="let d of data; let in=index; trackBy:trackByIndex">
    <input type="checkbox" 
           name="value" 
           [(ngModel)]="data[in].value"
           [(checked)]="data[in].value" 
           (change)="checkChanged($event)"/>
    {{d.text}}
  </div>      
</form>

我了解到,在 ngFor 中使用原语时,您需要我们 trackBy,所以这是我的 trackByIndex:

public trackByIndex(index: number, data: TextValuePair): any {
   return index;
}

这是数据:

public data = [{ text: "Human", value: true }, { text: "Dog", value: false }]

如果列表中的对象将value 设置为“true”,我需要在加载时检查复选框

【问题讨论】:

    标签: angular data-binding primitive ngfor


    【解决方案1】:

    发现问题。 &lt;form&gt; 内部变得混乱。删除&lt;form&gt;,您可以将代码简化为此。

      <div *ngFor="let d of data">
        <input type="checkbox" 
               name="data" 
               value="{{d.text}}"
               [(ngModel)]="d.value"
               (change)="checkChanged($event)"/>
        {{d.text}}
      </div>
    

    它应该可以工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-25
      • 2017-12-18
      • 1970-01-01
      • 2019-07-01
      • 2017-03-02
      • 1970-01-01
      • 2020-07-16
      相关资源
      最近更新 更多