【问题标题】:Angular [(ngModel)] changing data after other events fireAngular [(ngModel)] 在其他事件触发后更改数据
【发布时间】:2020-09-25 04:22:31
【问题描述】:

我不是 Angular 事件方面的专家,但这是我的问题。如果我运行以下代码,我基本上会用错误的信息更新后端,因为item.their_platformtogglePlatform() 触发之前不会改变。

模板:

<mat-checkbox (ngModelChange)="togglePlatform()" [(ngModel)]="item.their_platform"></mat-checkbox>

TS:

 togglePlatform(){
      //update backend with the new value for item.their_platform
  }

我已经通过在 togglePlatform 方法中使用超时解决了这个问题,但我希望有一个不同的事件我可以将该方法绑定到这在这种情况下更有意义。

还有更好的活动吗? 这是使用 mat-checkbox 与使用 vanilla Angular 的副作用吗?

谢谢

【问题讨论】:

    标签: angular typescript angular-material


    【解决方案1】:

    您可以使用change 而不是ngModelChange。因为 change 在 binding 之后触发,所以 ngModelChange 在 binding 之前触发。

    <mat-checkbox (change)="togglePlatform()" [(ngModel)]="item.their_platform"></mat-checkbox>
    

    【讨论】:

    • 是的,我也喜欢这个。谢谢
    • 欢迎您阅读本文以了解 change 和 ngModelChange 之间的区别。基本上 ngModelChange 在绑定之前触发,在绑定之后触发。 stackoverflow.com/questions/44840735/…
    【解决方案2】:

    不要依赖执行的顺序,因为您并不总是先到达。 在您的情况下,解决方案应该是:

    <mat-checkbox (ngModelChange)="togglePlatform($event)" [(ngModel)]="item.their_platform"></mat-checkbox>
    
    togglePlatform(value) {
         // update backend with the value, not item.their_platform
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 2017-05-09
      • 1970-01-01
      • 2019-01-30
      • 1970-01-01
      相关资源
      最近更新 更多