Issue
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!
Solution
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"
Answered By - Mike S.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.