* ng对原始数据类型的行为

问题描述 投票:4回答:1

我有一个对象列表,我在HTML页面上使用*ngFor显示。现在,用户与U​​I交互并更改其中一个原始值(boolean,从false变为true)。

根据我的理解,*ngFor将仅在列表对象被完全修改时呈现更改,即删除并再次添加到列表中。如果我对这个概念是正确的,那么请您建议一种方法来反映基元类型的变化,而无需重新初始化组件或修改对象引用。

例如:

  <div *ngFor="let item of list">
        <md-checkbox [(ngModel)]="item.selected"></md-checkbox>
  </div>

用户单击该复选框,但必须在从服务器进行某些验证后勾选复选框。因此,假设需要取消选中该复选框,并且用户会在小吃店上收到消息。所以我遍历列表并将item.selected修改为false。但是,当我修改对象项中选择的原始类型(布尔值)时,不会反映更改。那么如何在不重新加载或再次初始化页面的情况下呈现新值。

如果需要更多输入,请告诉我。

angular angular2-template
1个回答
5
投票

如果使用原始值,则需要trackBy

  <div *ngFor="let item of list trackBy:trackByIdx">
        <md-checkbox [(ngModel)]="item.selected"></md-checkbox>
  </div>
  trackByIdx(index: number, obj: any): any {
    return index;
  }

另见Angular2 NgFor inside tree model: wrong order when remove and then add elements

根据下面的讨论更新

更改输入值时更改ngModel限制的布尔值可能导致ngModel未更新。可以使用添加人工更改和callign detectChanges来解决问题。

constructor(private cdRef:ChangeDetectorRef) {}

deactivate(index: number) {
  this.list[index][0] = true;
  this.cdRef.detectChanges();
  this.list[index][0] = false;
  this.cdRef.detectChanges();
  console.log(this.list);
}

Plunker example

© www.soinside.com 2019 - 2024. All rights reserved.