【问题标题】:ngFor not removing old entries from list when array updatedngFor 在数组更新时不从列表中删除旧条目
【发布时间】:2018-03-29 02:39:09
【问题描述】:

我正在使用 ngFor 遍历一个简单的数组以输出列表项。

在某些时候,我想重新创建数组内容并更新 ngFor 内容。将数据推送到数组似乎按预期工作(即,该项目被添加到组件模板中列表的末尾)但是当我从头开始重新创建数组时,旧数据似乎没有被删除?

tests =  [{output: '1'}, {output: '2'}];
clear(){
    this.tests = [{output: '3'},{output: '4'}];
    // this.tests.push({output:'b'});
}

模板

<button (click)="clear()">Clear</button>
<ul>
   <li *ngFor="let test of tests">{{test.output}}</li>
</ul>

预期的输出应该是 1,2 的列表,单击按钮时,将列表重新创建为 3,4。相反,我得到的是:3,4,1,2(旧数据在最后保留并且没有从 DOM 中删除?)在 1,2,b 中正确使用推送结果(最后附加了 b)。

我做错了什么?如何有效地重新创建数组的内容并要求 ngFor 删除旧的 DOM 并正确地重复内容?

我尝试过手动使用触发事件更改(例如 changeDetectorRef 和 NgZone 甚至顶级应用程序引用),但它们都没有按预期工作。

【问题讨论】:

  • 你的代码对我有用
  • 奇怪,我刚刚设置了一个 Plunkr 来测试它,它确实按预期工作。但在我的本地应用程序上,我似乎无法让它工作。任何想法为什么会这样?请参见下面的 gif。 gyazo.com/fbfa505ae7bab0bd117c49e8c7c14588
  • 噢!在解决这个问题超过 2 小时后,问题是由另一个模块的控制台中的一些不相关的错误引起的。猜猜它以某种方式干扰了修改 DOM。感谢大家的帮助。
  • @NJ。你救了我的命。

标签: javascript angular ngfor


【解决方案1】:

试试这个可能有用

tests =  [{output: '1'}, {output: '2'}];
clear(){
    this.tests = [];
    this.tests = [{output: '3'},{output: '4'}];
    // this.tests.push({output:'b'});
}

【讨论】:

    【解决方案2】:

    我建议不要替换 tests 变量的值,而是首先通过设置 tests.length = 0 使其为空,然后通过 push 添加值:

    tests =  [{output: '1'}, {output: '2'}];
    
    clear() {
        this.tests.length = 0;
        this.tests.push(...[{output: '3'}, {output: '4'}]);
    }
    

    【讨论】:

      【解决方案3】:

      看看这个 plunker,它达到了预期的效果

      https://plnkr.co/edit/WzPdaD1AYfmJxLhhYZnk?p=preview

      //our root app component
      import {Component, NgModule, VERSION} from '@angular/core'
      import {BrowserModule} from '@angular/platform-browser'
      
      @Component({
        selector: 'my-app',
        template: `
          <div>
            <h2>Hello {{name}}</h2>
            <button (click)="clear()">Clear</button>
      <ul>
         <li *ngFor="let test of tests">{{test.output}}</li>
      </ul>
          </div>
        `,
      })
      export class App {
        name:string;
        tests =  [{output: '1'}, {output: '2'}];
        constructor() {
          this.name = `Angular! v${VERSION.full}`
        }
        clear(): void {
          this.tests =  [{output: '3'}, {output: '4'}];
        }
      }
      
      @NgModule({
        imports: [ BrowserModule ],
        declarations: [ App ],
        bootstrap: [ App ]
      })
      export class AppModule {}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-31
        • 1970-01-01
        • 2020-09-07
        相关资源
        最近更新 更多