ngStyle被激活了两次



我的按钮上有一个ngStyle。——在

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

当我点击它时,就会发生这种情况->

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

所以它为我的按钮设置了一个随机位置。但是当我点击我的按钮时,它会重新定位两次。

(点击功能只是播放声音和改变变量)

请帮忙!

不要在模板中使用函数。它们在每个应用程序周期中被调用,并且可以根据你的代码非常频繁地运行。

避免这种情况的一种方法是计算该值并将其分配给组件中的一个属性,然后使用该属性绑定到ngStyle。这样函数只会被调用一次。
this.compStyle = { marginLeft: Math.floor(Math.random() * 83) + 1   + 'vw', marginTop: Math.floor(Math.random() * 145) + 1   + 'vw' }

模板:

[ngStyle]="compStyle"

每次在组件中运行变更检测时,都会调用getRandomPos

如果你想控制变更检测在组件中何时运行,使用OnPush更改检测策略。

您也可以分离ChangeDetectorRef,只通过手动调用detectChanges来更新视图。

但是这完全没有必要,我只是在解释angular是如何工作的。

要解决这个问题,可以使用保存位置的属性:

buttonPos: Record<string, string>;

然后只在必要时更新它-无论是在水龙头还是其他地方。

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

在模板中使用按钮位置

[ngStyle]="buttonPos"

最新更新