仅当结果为真时,如何才能使我的mat-slide-toggle更改?

时间:2018-07-17 09:18:17

标签: angular typescript angular-material

我具有是否激活mat-slide-toggle的功能。我想只在结果为假时才更改此功能。但是,无论结果为真还是假,我的开关都会一直更改。我希望当结果为假时开关不会改变。

组件ts

onActiveHomeboxP(homeboxpackageid, activeid, elem) {
    this.areWeWaiting = true;
    if (confirm('Are you sure to change Status?')) {
      let editHomeboxp = new HomeboxP(
        this.activeHomeboxPForm.value
      );
      editHomeboxp.homeboxpackage_id = homeboxpackageid;
      editHomeboxp.active = !activeid ? 1 : 0;
      this.ws.activatehomeboxp(editHomeboxp).subscribe(
        result => {
          if (result === true) {
            this.router.navigate(['/hbp']);
          } else {
            this.areWeWaiting = false;
          }
        },
        error => {
        }
      );
    } else {
      elem.checked = !elem.checked;
    }
  }

组件html

<form [formGroup]="activeHomeboxPForm" class="col s12" >
        <span *ngIf="item.active === 1" >
          <section class="example-section">
            <mat-slide-toggle formControlName="active-{{item.homeboxpackage_id}}" class="example-margin" [checked]="item.active === 1" #elem (click)="onActiveHomeboxP(item.homeboxpackage_id, item.active, elem)" >
              </mat-slide-toggle>
          </section>
        </span>
         <span *ngIf="item.active === 0" >
          <section class="example-section">
            <mat-slide-toggle formControlName="active-{{item.homeboxpackage_id}}" class="example-margin" [checked]="item.active === 0" #elem (click)="onActiveHomeboxP(item.homeboxpackage_id, item.active, elem)">
               </mat-slide-toggle>
          </section>
        </span> 
   </form>

请,您能问我任何想法吗,如果结果为假,我如何不改变开关。 thnx

2 个答案:

答案 0 :(得分:0)

如果您想禁用该按钮(如果值为false),请使用ViewChild像这样获取mat-slide-toggle的引用

 @ViewChild('r') ref:ElementRef;

然后将模板ref添加到您的mat-slide-toggle元素

<mat-slide-toggle #r (click)="click()">Slide me!</mat-slide-toggle>

然后在您的欲望函数集中将其选中为真

   if(false){
       this.ref.checked =true
    }

在此处检查此示例:https://stackblitz.com/edit/angular-vybgss

答案 1 :(得分:0)

html文件:

<mat-slide-toggle [checked]="yourFlag">Slide me!</mat-slide-toggle>

ts文件:

func(){
     this.yourFlag = true;
}

如果YourFlag为true,则切换开关将打开,反之亦然。