0

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: enter image description here

Wayne Wei
  • 2,907
  • 2
  • 13
  • 19

1 Answers1

3

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>
javiens
  • 61
  • 1
  • 8
  • 21
ruth
  • 29,535
  • 4
  • 30
  • 57