* ng对于基本数据类型的行为 [英] *ngFor Behaviour on primitive data type

查看:79
本文介绍了* ng对于基本数据类型的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要在HTML页面上使用*ngFor显示的对象列表.现在,用户可以与UI交互并更改原始值之一(布尔值,从false更改为true).

I have a list of objects which I am displaying using a *ngFor on the HTML page. Now the user interacts with UI and changes one of the primitive values(boolean, from false to true).

据我了解,*ngFor仅在完全修改列表对象(即将其删除并再次添加到列表中)后才会呈现更改.如果我对这个概念是正确的,那么您能否建议一种方法来反映基本类型的更改,而无需重新初始化组件或修改对象引用.

As per my understanding the *ngFor will only render the changes if the list object is modified completely i.e. removed and added again to the list. 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.

例如:

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

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

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. 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.

推荐答案

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

If you use primitive values, you need 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;
  }

另请参见 根据下面的讨论更新

更改输入值时更改由ngModel绑定的布尔值,可能会导致ngModel无法更新.添加人为更改和callign detectChanges可用于解决此问题.

Changing a boolean value bound by ngModel when the input value is changed, may cause ngModel not being updated. Adding an artificial change and callign detectChanges can be used to work around.

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);
}

柱塞示例

这篇关于* ng对于基本数据类型的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆