Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

css - ngStyle is activating twice

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!

question from:https://stackoverflow.com/questions/65847033/ngstyle-is-activating-twice

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...