Angular 在鼠标移动时不断评估 ngStyle 表达式
Angular evaluating ngStyle expression constantly on mouse move
我想知道这是标准行为还是我做错了什么。基本上,我已经为 ngStyle 分配了一个 returns 可观察到的函数,每次鼠标移动时都会触发该函数。
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、承诺等,变更检测将 运行 所有组件.
要解决此问题,您可以更改检测策略以使用 ChangeDetectionStrategy.OnPush
。这告诉 Angular 该组件只依赖于它的 @Input()
。
OnPush
策略将 运行 仅在 @Input()
更改时更改检测。
@Component({
selector: 'app-component',
templateUrl: './app-component.component.html',
styleUrls: ['./app-component.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
我想知道这是标准行为还是我做错了什么。基本上,我已经为 ngStyle 分配了一个 returns 可观察到的函数,每次鼠标移动时都会触发该函数。
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、承诺等,变更检测将 运行 所有组件.
要解决此问题,您可以更改检测策略以使用 ChangeDetectionStrategy.OnPush
。这告诉 Angular 该组件只依赖于它的 @Input()
。
OnPush
策略将 运行 仅在 @Input()
更改时更改检测。
@Component({
selector: 'app-component',
templateUrl: './app-component.component.html',
styleUrls: ['./app-component.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})