简体   繁体   中英

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.

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 ?

By default Angular uses the ChangeDetectionStrategy.Default change detection strategy. 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.

To solve this issue, you can change detection strategy to use ChangeDetectionStrategy.OnPush . This tells Angular that the component only depends on its @Input() .

OnPush strategy will run change detection only when @Input() changed.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM