Angular 在鼠标移动过程中,角度样式的表达不断变化

Angular 在鼠标移动过程中,角度样式的表达不断变化,angular,rxjs,angular8,Angular,Rxjs,Angular8,我想知道这是标准行为还是我做错了什么。基本上,我已经分配了一个函数,该函数返回一个可观察到的ngStyle,它在每次鼠标移动时都会被触发 file.html <svg #image alt="First slide" class="img_carousel" [ngStyle] = "{'background': getImageForDocument(document) | async}"> </svg> file.ts getImageForDocume

我想知道这是标准行为还是我做错了什么。基本上,我已经分配了一个函数,该函数返回一个可观察到的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})`;

                }
            })
        );
    }
file.html
file.ts
getImageForDocument(文档、matBadge?):可见{
const carouselId=document.id;
返回此.store.select(fromStore.getAllImagesForDataObject(carouselId)).pipe(
地图(图像=>{
console.log('heree');
返回图像[0]。svg!=''?'center/不包含重复url(${images[0].image64Edit})`:'center/不包含重复url(${images[0].image64})`;
}
})
);
}

现在,当我在页面上移动鼠标时,我可以看到控制台不断打印。我希望只有当存储中的状态得到更新时才会触发。相反,ngStyle不断地计算表达式?

默认情况下,Angular使用
ChangeDetectionStrategy。默认情况下
ChangeDetectionStrategy。
默认策略不会对应用程序进行任何假设,因此,每当应用程序中的某些内容发生变化时(由于各种用户事件、计时器、XHR、承诺等),所有组件上都会运行变化检测

要解决此问题,可以将检测策略更改为使用
ChangeDetectionStrategy.OnPush
。这告诉Angular组件仅依赖于其
@Input()

OnPush
策略仅当
@Input()
更改时才会运行更改检测

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

这就是为什么永远不要在模板中放置函数调用。为什么需要将文档传递到此函数?为什么不在onInit中设置一次呢?这里的问题是将函数调用放在模板中,尤其是返回可观察的函数调用。这是一种可怕的做法,应该避免。Onpush变更检测有很多好处,但是这个问题应该从源头上解决。模板中的函数调用不是一种好的做法。可以使用自定义的
管道
对其进行修复
OnPush
应该可以解决这个问题,并且可以使用
pipe