angular2 template - How to add and remove CSS class names in Angular 2? -
i data in json format , must , must handle item user clicked on. i'm write code , correctly work.
my example dom-usage:
@component({ selector: 'my-app', template: ` <div *ngfor="let person of personslist; let = index"> <span class="toggle-icon" (click)="togglestatus(person.id)" id="{{person.id}}">{{person.name}}</span> </div> `, styles: ['.active { color: red; }'] }) export class app { toggleisactive: boolean = false; personslist: any; constructor() { this.personslist = [ { "id": "1", "name": "alex" }, { "id": "2", "name": "john" } ] } togglestatus(id){ const span = document.getelementbyid(`${id}`); if (span.classname.indexof('active') >= 0) { span.classlist.remove('active'); } else { span.classlist.add('active'); } } }
how can add , remove css class names without dom similar case?
i'm add "personisactive" field, , use class binding.
@component({ selector: 'my-app', template: ` <div *ngfor="let person of personslist; let = index"> <span class="toggle-icon" [class.active]="person.personisactive" (click)="togglestatus(person.id)">{{person.name}}</span> </div> `, styles: ['.active { color: red; }'] }) export class app { toggleisactive: boolean = false; personslist: any; constructor() { this.personslist = [ { "id": "1", "name": "alex", "personisactive": false }, { "id": "2", "name": "john", "personisactive": false } ] } togglestatus(id){ (let = 0; < this.personslist.length; i++) { if (this.personslist[i].id === id) { this.personslist[i].personisactive= !this.personslist[i].personisactive; } } } }
Comments
Post a Comment