简体   繁体   English

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

[英]*ngFor Behaviour on primitive data type

I have a list of objects which I am displaying using a *ngFor on the HTML page. 我有一个对象列表,我在HTML页面上使用*ngFor显示。 Now the user interacts with UI and changes one of the primitive values(boolean, from false to true). 现在,用户与U​​I交互并更改其中一个原始值(boolean,从false变为true)。

As per my understanding the *ngFor will only render the changes if the list object is modified completely ie removed and added again to the list. 根据我的理解, *ngFor将仅在完全修改列表对象时呈现更改,即删除并再次添加到列表中。 If I am right on this concept, then can you please suggest a method to reflect the change in the primitive type without re-initializing the component or modifying the object reference. 如果我对这个概念是正确的,那么请您建议一种方法来反映基元类型的变化,而无需重新初始化组件或修改对象引用。

For Example: 例如:

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

User clicks on the checkbox, but the checkbox has to be ticked after certain validations from server. 用户单击该复选框,但必须在从服务器进行某些验证后勾选复选框。 So let's say the checkbox needs to be unchecked and user gets a message on snack bar. 因此,假设需要取消选中该复选框,并且用户会在小吃店上收到消息。 So I loop through the list and modify item.selected to false. 所以我遍历列表并将item.selected修改为false。 But, the change is not reflected as i modified the primitive type selected(boolean) in the object item. 但是,当我修改对象项中选择的原始类型(布尔值)时,不会反映更改。 So how to render the new value without reloading or initializing the page again. 那么如何在不重新加载或再次初始化页面的情况下呈现新值。

Please let me know if more input is required. 如果需要更多输入,请告诉我。

If you use primitive values, you need trackBy 如果使用原始值,则需要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;
  }

See also Angular2 NgFor inside tree model: wrong order when remove and then add elements 另请参见Angular2 NgFor内部树模型:删除后添加元素的顺序错误

update according to the discussion below 根据下面的讨论更新

Changing a boolean value bound by ngModel when the input value is changed, may cause ngModel not being updated. 更改输入值时更改由ngModel绑定的布尔值可能导致ngModel未更新。 Adding an artificial change and callign detectChanges can be used to work around. 添加人工更改和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 Plunker的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM