How to add and remove CSS class names in Angular 2?

Home / Uncategorized / How to add and remove CSS class names in Angular 2?

Question:
I get the data in the JSON format and must and I must to handle which item the user clicked on. I’m write this code and it correctly work.

My Example with DOM-usage:@Component({
selector: ‘my-app’,
template: `

{{person.name}}

`,
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 I can add and remove CSS class names without DOM for a similar case?


Answer:
I’m just add "personIsActive" field, and use Class binding.
@Component({
selector: ‘my-app’,
template: `

{{person.name}}

`,
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){
for (let i = 0; i < this.personsList.length; i++) { if (this.personsList[i].id === id) { this.personsList[i].personIsActive= !this.personsList[i].personIsActive; } } } } Read more

Leave a Reply

Your email address will not be published. Required fields are marked *