簡體   English   中英

在鼠標移動時不斷評估AngStyle的角度

[英]Angular evaluating ngStyle expression constantly on mouse move

我想知道這是標准行為還是在這里做錯了。 基本上,我分配了一個函數,該函數將可觀察到的返回給ngStyle,每次鼠標移動時都會觸發該函數。

file.html


 <svg #image alt="First slide" class="img_carousel"
  [ngStyle] = "{'background': getImageForDocument(document) | async}">
</svg>


file.ts
getImageForDocument(document, matBadge?): Observable<string> {
        const carouselId = document.id;
 return this.store.select(fromStore.getAllImagesForDataObject(carouselId)).pipe(
            map(images => {
                console.log('heree');
 return images[0].svg !== '' ? `center / contain no-repeat url(${images[0].image64Edit})` : `center / contain no-repeat url(${images[0].image64})`;

                }
            })
        );
    }

現在,即使在頁面上移動鼠標,也可以看到控制台不斷打印。 我希望只有在商店中的狀態更新時才會觸發此操作。 相反,ngStyle會不斷評估表達式?

默認情況下,Angular使用ChangeDetectionStrategy.Default更改檢測策略。 默認策略不假設有關該應用程序的任何內容,因此,由於各種用戶事件,計時器,XHR,promise等的結果,每次我們的應用程序發生更改時,都會在所有組件上運行更改檢測。

要解決此問題,可以將檢測策略更改為使用ChangeDetectionStrategy.OnPush 這告訴Angular該組件僅取決於其@Input()

僅當@Input()更改時, OnPush策略才會運行更改檢測。

@Component({
    selector: 'app-component',
    templateUrl: './app-component.component.html',
    styleUrls: ['./app-component.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})

暫無
暫無

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

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