[英]Angular evaluating ngStyle expression constantly on mouse move
I am wondering if this is standard behaviour or am I doing something wrong here. 我想知道这是标准行为还是在这里做错了。 Basically I have assigned an a function that returns an observable to ngStyle which is triggered every time 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})`;
}
})
);
}
Now I can see the console printed constantly when I even move the mouse on the page. 现在,即使在页面上移动鼠标,也可以看到控制台不断打印。 I would expect that this is triggered only when the state in the store gets updated.
我希望只有在商店中的状态更新时才会触发此操作。 Instead ngStyle is evaluating the expression constantly ?
相反,ngStyle会不断评估表达式?
By default Angular uses the ChangeDetectionStrategy.Default
change detection strategy. 默认情况下,Angular使用
ChangeDetectionStrategy.Default
更改检测策略。 The default strategy doesn't assume anything about the application, therefore every time something changes in our application, as a result of various user events, timers, XHR, promises, etc., a change detection will run on all components. 默认策略不假设有关该应用程序的任何内容,因此,由于各种用户事件,计时器,XHR,promise等的结果,每次我们的应用程序发生更改时,都会在所有组件上运行更改检测。
To solve this issue, you can change detection strategy to use ChangeDetectionStrategy.OnPush
. 要解决此问题,可以将检测策略更改为使用
ChangeDetectionStrategy.OnPush
。 This tells Angular that the component only depends on its @Input()
. 这告诉Angular该组件仅取决于其
@Input()
。
OnPush
strategy will run change detection only when @Input()
changed. 仅当
@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.