angular2 forms - Checkbox filter in Angular 2 -
i have array of objects (tasks) in table , 2 checkboxes: "night", "day".
i want next scenario: if checkbox night checked, tasks property "night" left in table. if checkbox day checked, tasks property "day" left in table (and "night" tasks left if checkbox "night" still checked). , third checkbox "reset" resets filter.
maybe it's better use way sorting, example pipes?
here's plunkr. here's code:
@component({ selector: 'my-app', template: ` <input type="checkbox" (click)="getnight()">night <input type="checkbox" (click)="getday()">day <input type="checkbox">uncheck <br><br> <table> <tr *ngfor="let task of tasks"> <td>{{task.chkboximageurl}}</td> <td>{{task.id}}</td> <td>{{task.val}}</td> </tr> </table> `, }) export class app { tasks: array<{chkboximageurl: string, id: string, val: string, checked:boolean}> = [ {chkboximageurl: "http1", id: "item1", val: "night", checked: false}, {chkboximageurl: "http2", id: "item2", val: "day", checked: false}, {chkboximageurl: "http3", id: "item3", val: "night", checked: false}, {chkboximageurl: "http4", id: "item4", val: "day", checked: false}, {chkboximageurl: "http4", id: "item4", val: "morning", checked: false}, {chkboximageurl: "http4", id: "item4", val: "evening", checked: false} ]; getnight() { console.log(this.tasks[2].val); // night // return this.tasks.filter(obj => obj.checked).map(obj => obj.val); if(this.tasks.val == 'night') { return this.tasks.filter(obj => obj.checked).map(obj => obj.val == 'night'); } else { console.log('666666'); } }; getday() { return this.tasks.filter(obj => obj.checked).map(obj => obj.val); }; getcheckedcount(){ return this.getcheckedvalues().length; } }
updated plunkr here
in order filter tasks array night , day checkbox values need accessible. 1 way of doing creating instance variables night , day , using ngmodel directive bind them respective checkboxes.
component:
night: boolean = false; day: boolean = false; view:
<input type="checkbox" [(ngmodel)]="night">night <input type="checkbox" [(ngmodel)]="day">day night , day true when checked , false when unchecked. these values can used filter tasks array.
component:
interface task { chkboximageurl: string; id: string; val: string; checked:boolean; } gettasks(): array<task> { return this.tasks.filter(obj => this.night && obj.val === 'night' || this.day && obj.val === 'day'); } view:
<tr *ngfor="let task of gettasks()"> the gettasks() method returns array of tasks, filtered conditionally on values of night , day. bound view.
to clear checkboxes when uncheck checkbox checked, values of night , day can reset false.
component:
uncheck() { this.night = false; this.day = false; } view:
<input type="checkbox" (click)="uncheck()">uncheck on click, other checkboxes reset changes result of gettasks()
Comments
Post a Comment