角度/材质的垫滑动切换功能

时间:2019-10-22 06:52:38

标签: angular angular-material

我正在使用mat-slide-toggle更改某些设置。 HTML代码如下:

import APIService from '../../utils/APIService';

Page.getInitialProps = async function({ res, query }) {

  const req = await APIService.get('/endpoint', {});

  const { data } = req;

  return {
    data
  };
};

<mat-slide-toggle type="checkbox" class="form-control" color="#3f9f94" [checked]="clickDataLogEnabled" [(ngModel)]="clickDataLogEnabled" (click)="onClick('clickData')"> Log User Click data</mat-slide-toggle><br> 的初始值为true。

点击功能如下:

clickDataLogEnabled

当我单击按钮时,首个console.log("clickData log "+this.clickDataLogEnabled); //this.settingsService.setClickDataLogEnabled(!this.clickDataLogEnabled); this.clickDataLogEnabled = !this.clickDataLogEnabled; console.log("clickData log2 "+this.clickDataLogEnabled); //this.settingsService.updateSettings(); 给出true(1),下一个console.log给出false(0)。但是,当我再次单击它时,当顺序应该更改时,我会以相同的顺序获得相同的输出。另外,当我单击时,按钮仍保持切换状态。我必须滑动它才能更改UI,但是那时控制台上没有日志。有人可以告诉我我在做什么错。谢谢。

1 个答案:

答案 0 :(得分:0)

您不必通过clickDataLogEnabled方法手动更改onClick。如果仅使用[checked]属性,则必须这样做。我建议您不要同时使用[checked][(ngModel)]

如果您使用[(ngModel)],则无需处理切换逻辑,因为它将自动完成。 (当您单击/切换时,您的clickDataLogEnabled将会更改)。

模板:

<mat-slide-toggle type="checkbox" class="form-control" color="#3f9f94" 
        [(ngModel)]="clickDataLogEnabled" (click)="onClick('clickData')">
        Log User Click data</mat-slide-toggle><br>

点击功能现在应该可以了。您不必执行切换逻辑。

console.log("clickData log " + this.clickDataLogEnabled);
// this.clickDataLogEnabled = !this.clickDataLogEnabled; Remove This Line
相关问题