簡體   English   中英

僅運行一次 Angular 更改檢測並停止檢測該組件的更改

[英]Run Angular change detection only once and stop detecting changes for that component

我只需要在加載組件或路由發生變化時檢測一次角度變化,然后我想停止檢測變化。

實際上我需要根據用戶角色顯示和隱藏功能。 所以我在一個 html 模板中有很多*ngIf但我只需要在模板第一次加載時檢查一次*ngIf條件,然后停止檢測更改,因為它影響性能。

我希望頁面在單次更改檢測后像靜態一樣。

例如 :

       <li *ngIf="doesHavePermission('templateName')">
       </li>

應該檢查一次,但我看到的是它正在多次檢查單個*ngIf的更改,我有很多*ngIf像這樣:

我在這個角度文檔https://angular.io/api/core/ChangeDetectorRef 中找到了markForCheck()detach()

但他們正在做的是他們要么允許所有更改檢測,要么根本不允許,

而且我只需要檢測一次更改並在此之后停止。

我們可以在角度上進行單次時間變化檢測嗎?

或者有更好的方法來處理場景嗎?

當您在*ngIf使用函數調用時,每次發生更改檢測時 angular 都會調用此函數。 這個 changeDetection 是在你的組件外部還是內部觸發都沒有關系,但是 angular 在調用這個函數之前無法知道函數的返回值是否已經改變。

因此,通常在*ngIf中使用函數調用並不是一個好方法。

備擇方案:

在組件中使用普通屬性:

instead of 
<div *ngIf="checkCondition()"></div>

use this

<div *ngIf="condition"></div>

@Component(...)
class MyComponent {
 condition= false;

 checkCondition() {
  if(something) {
   this.condition = true;
  }
 }
}

使用這種方法,您可以在條件發生變化時更好地處理並手動調用該函數。 除了使用屬性,您還可以使用地圖:

@Component(...) 
class MyComponent{
  conditions: { [key: string]: boolean }

  ngOnInit() {
   condition = {
    template1: true,
    template2: false
   }
  }
}

<div *ngIf="conditions['template1']"></div>

在與組合ChangeDetectionStrategy.OnPush可以最大限度地減少changedetection作為onPush當輸入PARAMS改變才會觸發變化檢測。 這基本上意味着來自父項的更改檢測不會觸發子項的更改檢測。

如果你結合這兩種方法,你應該得到最小的變化檢測:

@Component({
...
changeDetection: ChangeDetectionStrategy.OnPush
}) 
    class MyComponent{
      @Input() conditions: { [key: string]: boolean }
}

這是一篇可供進一步閱讀的好文章: https : //medium.com/showpad-engineering/why-you-should-never-use-function-calls-in-angular-template-expressions-e1a50f9c0496

您可以只使用ChangeDetectorRef注入器的detach方法從變更檢測周期中刪除當前組件。 您可以隨時撥打reattach方法或手動調用detectChanges通過修改,使快速運行。

對我來說,這是最可靠的方式。

但請注意,它始終會關閉所有孩子的變化檢測!

暫無
暫無

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

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