[英]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.