在循环中添加类名单击项目* ngFor Angular 2

时间:2016-11-16 12:14:45

标签: angularjs angular typescript ionic2

我遇到了基于Angular 2 ngFor循环索引添加类名的问题。使用ngFor创建多个按钮,当我单击按钮时在特定按钮中添加类。喜欢标签选择供您参考Link

<button color="light" *ngFor="let category of categories" [class.tagactive]='stateOfButton' (click)="changeState(i)" let i = index;>{{category}} <span (click)="delete(i)">X</span></button>

    stateOfButton: boolean = false;
    categories = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado', 'mango'];
    changeState(index) {
        this.stateOfButton = !this.stateOfButton;
    }
    delete(index) {
      this.categories.splice(index, 1);
    }

.tagactive { background: #cc3333; color:#fff;}

1 个答案:

答案 0 :(得分:1)

您需要array来管理按钮的有效或无效状态:

//HTML
<button color="light" *ngFor="let category of categories;let i = index;" [class.tagactive]="stateOfButton[i]" (click)="changeState(i)">{{category}} <span (click)="delete(i)">X</span></button>


// Component
categories = ['Windstorm', 'Bombasto', 'Magneta', 'Tornado', 'mango'];
stateOfButton: boolean[];

ngOnInit() {
  // Creates the array with inactive state initially for all category items. 
  this.stateOfButton = Array(this.categories.length).fill(false);
}

changeState(index) {
    this.stateOfButton[index] = !this.stateOfButton[index];
}
delete(index) {
  this.categories.splice(index, 1);
  this.stateOfButton.splice(index, 1);
}