[英]Why [ngStyle] is called many times during page rendering?
我有一個使用[ngStyle] = "getStyle()"
的 Angular 頁面,當我運行該頁面時,似乎 getStyle() 已被多次調用。 誰能解釋為什么會發生這種行為?
模板:
<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代碼:
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'
};
如果您使用默認的更改檢測策略,則將在每個更改檢測周期調用綁定到屬性和指令的函數。 像{{ getStyle() }}
這樣的插值函數也是如此。
您需要在 controller 中運行一次 function,將其結果保存在變量中,並將屬性綁定到它。
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'
};
}
}
模板
<div class="toast" data-autohide="false" [ngStyle]="style">
...
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.