简体   繁体   中英

Why [ngStyle] is called many times during page rendering?

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: 在此处输入图像描述

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>

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