簡體   English   中英

如何通過 Angular 中的一個簡單類變量消除更改檢測並防止重新渲染?

[英]How can i cut away change detecion and prevent rerender by a simple class variable in Angular?

我制作了一個非常簡單的演示應用程序來解釋我想要做什么。

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  a=1
  b=2
    
  increase(){
    this.a++
    this.b++
  }
}

模板:

<p>{{ a }}</p>
<p>{{ b }}</p>
<button type="button" (click)="increase()">Increase</button>

當我單擊顯示“變量a”更改但“變量b”沒有更改時單擊增加按鈕時,我如何實現它。我的意思是只是在顯示...

b設為私有並為模板綁定使用不同的變量bDisplay 然后,您可以跟蹤b的值並在需要時通過更新bDisplay來更新視圖。

除此之外,我沒有看到任何解決方案。 Angulars 的目標是保持模型和視圖同步,因此如果綁定值發生更改,您將無法在某個時候更新視圖。

在您的示例中,實際上有一種方法可以在第一次單擊按鈕時不更新視圖中的b (但它會在第二次單擊時彌補):在組件中使用 ChangeDetectionStrategy.OnPush 並在 setTimeout 中增加b的值:

increase(): void {
  this.a++;
  setTimeout(() => {
    this.b++;
  });
}

a將在視圖中更新,因為單擊會觸發更改檢測周期並標記要檢查更改的組件。 之后,setTimeout 會過去,這會觸發一個新的 CD 周期,但不會標記要檢查的組件,因此b不會在視圖中更新。 但是下次單擊時, a將再次更新, b將在視圖中更新為第一次單擊時的值。

苗條說的對。 你基本上有2個選擇。 一個是他提到的改變變更檢測策略。 另一個是在角度之外運行它。

變更檢測策略 OnPush

使用 OnPush 代替默認的更改檢測策略,如下所示:

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
  /* ... */
  increase() {
    this.a++
    this._ngZone.runOutsideAngular(() => {
      setTimeout(() => {
        this.b++;
      });
    })
  }
}

吳區

或者(如果您不想切換到 OnPush),您可以在 Angular 之外運行它:

constructor(private _ngZone: NgZone) {}

increase() {
  this.a++
  this._ngZone.runOutsideAngular(() => {
    setTimeout(() => {
      this.b++;
    });
  })
}

這是Stackblitz上的一個示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM