Cpt Kitkat
Cpt Kitkat

Reputation: 1402

How to change Toggle Value for only 1 row not all

I have a mat-toggle as a column in Mat-table.I am changing values on toggle on/off. However the issue is if I change the value then the value changes for all the rows. I want to do it only for the particular row. How can I do it.

HTML Code:

<ng-container matColumnDef="active">
  <th mat-header-cell *matHeaderCellDef mat-sort-header>Reschedule</th>
  <td mat-cell *matCellDef="let element">
    <mat-slide-toggle (change)="setMessage($event)">{{
      message
    }}</mat-slide-toggle>
  </td>
</ng-container>

Typescript Code:

// Toggle Button Code
message = 'Disabled!';
setMessage(e) {
    if (e.checked) {
        this.message = 'Running';
    } else {
        this.message = 'Disabled!';
    }
}

Upvotes: 2

Views: 846

Answers (1)

zerocewl
zerocewl

Reputation: 12794

You need a property for every row to bind your toggle state to.

E.g.:

Component data:

....
const ELEMENT_DATA: PeriodicElement[] = [
  { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H', activate: true, role: '1' },
...

Template:

...
    <!-- toggle olumn -->
    <ng-container matColumnDef="toggle">
        <th mat-header-cell *matHeaderCellDef> toggle </th>
        <td mat-cell *matCellDef="let element" >
            <mat-slide-toggle [checked]="element.activate" (change)="updateActiveStatus(element)"></mat-slide-toggle>
        </td>
    </ng-container>
...

Check this Stackblitz for a working version.

Upvotes: 2

Related Questions