2017-08-15 76 views
0

我以JSON格式獲取數據,必須和我必須處理用戶點擊的項目。我寫這個代碼,它正確工作。如何添加和刪除Angular 2中的CSS類名?

我的例子與DOM的用法:

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div *ngFor="let person of personsList; let i = 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'); 
    } 
    } 
} 

如何我能爲一個類似的案件中添加和刪除CSS類名,而不DOM?

+0

https://angular.io/api/common/NgClass –

回答

0

我只是添加「personIsActive」字段,並使用Class binding

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div *ngFor="let person of personsList; let i = 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){ 
    for (let i = 0; i < this.personsList.length; i++) { 
     if (this.personsList[i].id === id) { 
     this.personsList[i].personIsActive= !this.personsList[i].personIsActive; 
     } 
    } 
    } 
}