fariba.j
fariba.j

Reputation: 1865

How to handle multiple mat-slide-toggle label in angular 6?

I'm using angular 6 and I have 4 mat-cards, each card has a status with a value of Active or Deactive. and each card has a mat-slide-toggle that change the status of the card. i want to change the Active status to Deactive when the slide-toggle changes from true to false. here are the codes:

card.html

<mat-grid-tile *ngFor="let card of cards">
        <mat-slide-toggle class="example-margin" (change)="onChange($event)" [disabled]="false" [checked]="true"  [(ngModel)]="card.status1" name="status">
          <span class="status">status: {{card.status}}</span>
        </mat-slide-toggle>
</mat-grid-tile>

card.ts

 ngOnInit() {
this.getDispensers();
}

    getDispensers() {
    this.dispenserService.getDispensers().subscribe(dispensers => {
      this.cards = dispensers;
      this.cards.forEach(item => {
        item.status1 = item.status == 'Deactive' ? false : true;
      });
    });
  }


 onChange(value) {
    console.log(value)
  }

I don't know how should I change the status. now I just see true and false in card.status

Upvotes: 2

Views: 6275

Answers (1)

G. Tranter
G. Tranter

Reputation: 17908

Because your card model data is different than the slide toggle model data, you can't directly bind the toggle to the card with [(ngModel)]="card.status1". Instead, use the toggle's [checked] and (change) to manually do the binding yourself:

<mat-grid-tile *ngFor="let card of cards">
    <mat-slide-toggle class="example-margin" (change)="onChange($event.checked, card)" [disabled]="false" [checked]="card.status === 'Active'" name="status">
        <span class="status">status: {{card.status}}</span>
    </mat-slide-toggle>
</mat-grid-tile>

ngOnInit() {
    this.getDispensers();
}

getDispensers() {
    this.dispenserService.getDispensers().subscribe(dispensers => {
        this.cards = dispensers;
    });
}


onChange(value, card) {
    card.status = value ? 'Active' : 'Deactive';
}

Upvotes: 3

Related Questions