首页 > 解决方案 > 使用 ngDoCheck() 的无限循环

问题描述

在玩弄时NgDoCheck()我得到了一个无限循环,我不知道如何或为什么。如果我运行它并检查浏览器控制台,我会看到ngDocheck()不断被调用。我只有 1 个组件,模板只是一个带有 3 个输入的表单(在stackblitz上)。有人可以帮忙吗?

export class AppComponent {

  testvar: number=0;
  product: Product= new Product();
  productOne: Product = new Product();
  productTwo: Product = new Product();

  constructor(){
    this.productOne.name="productOne";
    this.productOne.category="soccer";
    this.productOne.price=5.5;
    this.productTwo.name="productTwo";
    this.productTwo.category="basketball";
    this.productTwo.price=8.6;
  }

  submitForm(form: NgForm) {
    if (form.valid) {
      // this.model.saveProduct(this.product);
      this.product = new Product();
      form.reset();
    }
  }

  ngDoCheck(){
    console.log("I am called");
    this.product=new Product();
     let startvar = this.testvar;
     if(this.testvar==0){
       Object.assign(this.product, this.productOne  );
     }
    if(this.testvar==1){
       Object.assign(this.product, this.productTwo );
      this.testvar=0;
    }
   if(!(startvar==1&&this.testvar==0)){
    this.testvar++;
   }

  }

标签: angulartypescriptangular-changedetection

解决方案


ngDoCheck执行除了默认更改检测之外的其他更改检测检查。为了简单起见,当一个组件默认渲染时,会发生一个变化检测周期,其中ngOnInit就足够了。但是,假设您在组件渲染后从父组件进入组件的价值,那么您将不得不使用ngOnChanges检测该更改。此外,如果您需要检测除了来自 Angular 的默认检查之外的其他更改(例如:来自指令的更改),那么您将不得不使用ngDoCheck

但是,ngDoCheck确实很昂贵,因为即使您没有意识到,您也会对组件进行如此多的更改,其中可能包括在初始组件加载期间单击输入字段或从组件中的任何位置通过角度进行的更改。因此,即使在您开始在输入字段上输入之前,您也将执行数百次 ngDoChecks。这会大大降低应用程序的性能。除非你需要,否则不推荐。


推荐阅读