Angular 2:将相同的点击事件绑定到多个元素

3

我在组件的导出类中有iconCheck: string;,然后在构造函数中我有this.iconCheck = "add_circle";,在我的导出类中也有这个。

iconChange() {
    if(this.iconCheck == "add_circle") {
      this.iconCheck = "remove_circle"
    } else {
      this.iconCheck = "add_circle";
    }
  }

现在我有多个可折叠/可展开的HTML元素,我正在使用Bootstrap手风琴进行操作。我正在使用+/-图标切换。例如,第一次时所有手风琴都关闭且都显示+图标,但当我点击其中一个时,应该打开并将图标更改为(-)。

现在我遇到问题是,当我单击任何手风琴时,所有其他手风琴的图标也会更改为(-)图标。我需要找到一种方法来绑定点击事件到特定的手风琴元素。我不确定正确的术语是什么,也不知道如何解释,但我需要一个作用域限制或者绑定特定被点击的元素的点击事件。

以下是我的HTML代码:

<a data-toggle="collapse" (click)="iconChange()" href="#collapse1">
 Property 1 
 <i class="material-icons pull-right">{{iconCheck}}</i>
</a> 

<a data-toggle="collapse" (click)="iconChange()" href="#collapse2">
 Property 1 
 <i class="material-icons pull-right">{{iconCheck}}</i>
</a>
1个回答

4

我曾多次遇到这个问题。通常我使用某种索引来跟踪用户点击/打开的手风琴,并使用该提示切换图标。

我创建了这个简单的Plunker演示。看看是否符合您的要求 :)

app.ts:

export class App {
  name:string;

  selectedIndex: number;

  constructor() {
    this.name = `Angular! v${VERSION.full}`;
    this.selectedIndex = -1;
  }

  iconChange(index: number){
    if(this.selectedIndex == index){
      this.selectedIndex = -1;
    }
    else{
      this.selectedIndex = index;
    }

  }
}

模板:

<div>
  <h2>Hello {{name}}</h2>
  <div class="div1" (click)="iconChange(1)" >
    Hi 
      <i class="fa" [ngClass]="{'fa-plus': selectedIndex != 1, 'fa-minus': selectedIndex == 1}" aria-hidden="true" style="float: right"></i>
    </div>
  <div class="div2" (click)="iconChange(2)">
    Hi again!
      <i class="fa" [ngClass]="{'fa-plus': selectedIndex != 2, 'fa-minus': selectedIndex == 2}"  aria-hidden="true" style="float: right"></i>
  </div>
  <div class="div3" (click)="iconChange(3)">
    Bye!
      <i class="fa" [ngClass]="{'fa-plus': selectedIndex != 3, 'fa-minus': selectedIndex == 3}"  aria-hidden="true" style="float: right"></i>
  </div>
</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接