ngStyle is activating twice

Viewed 38

I have an ngStyle on my button. - >

<ion-button *ngIf="showBtn" (click)="tap()" [ngStyle]="getRandomPos()" fill="outline"> 

When i click it this happenes - >

getRandomPos()
  { 
    return { marginLeft: Math.floor(Math.random() * 83) + 1   + 'vw', marginTop: Math.floor(Math.random() * 145) + 1   + 'vw' }
  }

So It sets a random position for my button. But when i click my button, it's repositioning twice.

(The tap function is just playing a sound and changing a variable)

Please Help!

2 Answers

Don't use functions in your template. They are called on every application tick and can run very often depending on your code.

One way to avoid this is to compute the value and assign it to a property in your component and then use that property to bind to ngStyle. That way the function will only be called once.

this.compStyle = { marginLeft: Math.floor(Math.random() * 83) + 1   + 'vw', marginTop: Math.floor(Math.random() * 145) + 1   + 'vw' }

Template:

[ngStyle]="compStyle"

getRandomPos will get called every time the change detection runs in your component.

If you want to have control on when change detection runs in your component, use OnPush change detection stratagy.

You can also detach ChangeDetectorRef and only update the view by calling detectChanges manually.

But that is completely unnnecessary and an overkill, I'm just explaining how things work in angular.

To solve your problem, use a property in which you save the position:

buttonPos: Record<string, string>;

Then update it only when necessary - whether it is in tap or elsewhere.

updateButtonPos() { this.buttonPos = { marginLeft: Math.floor(Math.random() ... }} 

tap() {
    updateButtonPos()
} 

Use button position in template

[ngStyle]="buttonPos"
Related