Issue
I have an Angular page using [ngStyle] = "getStyle()"
, when i run the page, seems the getStyle() has been called many times.
Could anyone explain why this behavior is happening?
Template:
<div class="toast" data-autohide="false" [ngStyle]="getStyle()">
<div class="toast-header">
<strong class="mr-auto text-primary">{{comment.username}}</strong>
<small class="text-muted">5 mins ago</small>
</div>
<div class="toast-body">
{{comment.comment}}
</div>
</div>
TS code:
getStyle(): Object {
this.x = Math.floor((Math.random() * 100));
this.y = Math.floor((Math.random() * 30));
console.log('random process ', this.x, this.y);
return {
left: this.x+'px',
top: this.y+'px'
};
The log printed in browser console:
Solution
If you’re using default change detection strategy, the functions bound to properties and directives will be called for each change detection cycle. The same goes for having functions in interpolation like {{ getStyle() }}
.
You need to run the function once in the controller, save it’s result in a variable, and bind the property to it.
Controller
export class SomeComponent {
style: any;
ngOnInit() {
this.style = this.getStyle();
}
getStyle(): Object {
this.x = Math.floor((Math.random() * 100));
this.y = Math.floor((Math.random() * 30));
console.log('random process ', this.x, this.y);
return {
left: this.x + 'px',
top: this.y + 'px'
};
}
}
Template
<div class="toast" data-autohide="false" [ngStyle]="style">
...
</div>