如何防止在ngFor指令中调用组件的构造函数

巴托什·巴塞克

我可以在ngFor指令中包含组件吗,以这种方式,当数据更改时,不必每次都调用组件的构造函数?

Plunker示例:http ://plnkr.co/edit/6A6Aj8yeFqNd28Nl8cyS?p=preview

我只想更新数据,而不是重新创建组件。打开控制台,以更好地理解我的意思。

AppComponent:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <div *ngFor="let value of sourceData">
        <fizz [sampleInputValue]="value"></fizz>
      </div>
    </div>
  `,
})
export class App {

  sourceData: number[] = [];

  ngOnInit() {
    setInterval(() => {
      let newArrayOfRandomNumbers: number[] = [
        Math.floor(Math.random() * 60) + 1,
        Math.floor(Math.random() * 60) + 1,
        Math.floor(Math.random() * 60) + 1,
        Math.floor(Math.random() * 60) + 1,
        Math.floor(Math.random() * 60) + 1
      ]

      newArrayOfRandomNumbers.forEach((randomNumber, index) => {
        this.sourceData[index]= newArrayOfRandomNumbers[index];
      });
    }, 500);
  }
}

FizzComponent;

@Component({
  selector: 'fizz',
  template: `
    {{sampleInputValue}}  
  `
})
export class FizzComponent {

  @Input()sampleInputValue: number;

  constructor() {
    console.log("I dont want to be called, I just want the data to be updated")
  }
}
马克斯·科雷茨基(Max Koretskyi)

问题在于Angular使用默认的trackBy函数,该函数按身份进行比较。如果不匹配,它将重新创建组件并因此调用其构造函数。

您可以利用它,并将具有数字属性的值作为对象传递给ngFor

  sourceData = [{},{},{},{},{}];

  ngOnInit() {
    setInterval(() => {
      let newArrayOfRandomNumbers: number[] = [
        Math.floor(Math.random() * 60) + 1,
        Math.floor(Math.random() * 60) + 1,
        Math.floor(Math.random() * 60) + 1,
        Math.floor(Math.random() * 60) + 1,
        Math.floor(Math.random() * 60) + 1
      ]

      newArrayOfRandomNumbers.forEach((randomNumber, index) => {
        this.sourceData[index].v= newArrayOfRandomNumbers[index];
      });
    }, 500);

这将不会重新创建组件。看到这个笨蛋

另请参阅此答案以了解有关ngFor trackBy的更多信息。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章