【问题标题】:Angular2 ngFor: when add/remove DOM? how to force it recreate DOM?Angular2 ngFor:何时添加/删除 DOM?如何强制它重新创建 DOM?
【发布时间】:2017-05-08 19:28:18
【问题描述】:

我正在使用 Angular2 *ngFor 并且对它何时重新创建 DOM 有点困惑。

如果我在 onClick() 中只有 case 1 代码,那么它将重新创建两个 <li>,但我只是将相同的值分配给 this.objArr。

如果我在 onClick() 中只有 case 2 代码,那么它不会重新创建两个 <li>,而只需再添加一个 <li>。我想知道 ngFor 如何确定何时重新创建 DOM。

我想做的是

如果我只是将更多对象推送到现有数组中,除了为推送对象添加 DOM 之外,我如何让它为我重新创建现有 DOM?和案例 2 一样,我希望 ngFor 可以为我重新创建前两个 <li>

HTML:

 <button (click)="onClick($event)"></button>
    <li *ngFor="let obj of objArr"></div>

.ts 文件:

    constructor() {
         this.objArr = [
                    {
                        'id': 0,
                        'content': 'test0'
                    },
                    {
                        'id': 1,
                        'content': 'test1'
                    }
                ];
    }

   onClick() {
       // case 1: recreate two <li>
       this.objArr = [
                    {
                        'id': 0,
                        'content': 'test0'
                    },
                    {
                        'id': 1,
                        'content': 'test1'
                    }
                ];

        // case 2: just add one <li> after the two existing <li>
        this.objArr.push({
             'id': '2',
             'content': 'test2'
        });


   }

【问题讨论】:

  • 你可以使用管道
  • @VinayPandya 你能根据我的例子解释更多细节吗?

标签: angular ngfor


【解决方案1】:

您可以暂时将objArr 设置为 null 并通过在两者之间调用detectChanges 来“强制”Angular 更新 DOM:

constructor(private cdRef:ChangeDetectorRef) {}

onClick() {
  var tmp = this.objArr;
  this.objArr = null;
  this.cdRef.detectChanges();
  this.objArr = tmp;
  this.cdRef.detectChanges();
}

【讨论】:

  • 谢谢。 this.objArr = null;this.objArr = [ ]; 有什么区别? this.objArr = [ ]; 会保留原始引用吗?
  • 更改objArr 的值并运行更改检测会强制*ngFor 删除所有项目,然后将它们添加回去会使*ngFor 重新添加它们。
  • 我明白了。感谢您的帮助。
  • 你不能使用 OnPush 策略,然后cdRef.markForChange()
  • 我猜是这样,但问题中没有提到OnPush
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-21
  • 2016-06-19
  • 1970-01-01
  • 2023-01-24
  • 2011-10-24
  • 1970-01-01
相关资源
最近更新 更多