Deyvison Souto
Deyvison Souto

Reputation: 157

How can I put a number value in slide toogle Angular Material

I'd like to get all "id" from list items "checked"

<div *ngFor="let item of list">
   <md-slide-toggle [(ngModel)]="item.id">
       item.name
    </md-slide-toggle>
</div>

Upvotes: 0

Views: 1334

Answers (1)

Nehal
Nehal

Reputation: 13307

You can create a separate array that keep tracks of which item in the 'list' has been marked as true. Then, you can use the change output event to emit information about the item to your component and perform action on it.

Example code:

html:

<div *ngFor="let item of list; let i = index">
   <md-slide-toggle [checked]="flagArray[i]"
                    (change)="sendToServer($event, i, item)">
       {{item.name}}
    </md-slide-toggle>
</div> 

component.ts:

flagArray = [];

  list = [
    { id: '1', name: 'item 1'},
    { id: '2', name: 'item 2'},
    { id: '3', name: 'item 3'},
    { id: '4', name: 'item 4'},
  ]

  constructor(){
    for(let  i=0; i<this.list.length; i++){
      this.flagArray.push(false);
    }
  }

  sendToServer(event, index, item){ 
    this.flagArray[index] = event.checked;

    if(event.checked == true){
      // add code to send item to server
      alert("item to send to server: " + JSON.stringify(item));        
    }
    else{
      // add code to remove item from server
      alert("item to remove from server: " + JSON.stringify(item));
    }
  }

Plunker demo

Upvotes: 1

Related Questions