Angular 2 Binding one click event to multiple elements

I have iconCheck: string;

in my class export components, and inside the constructor I have this.iconCheck = "add_circle";

, and in my export class I have

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

      

Now I have mulitple foldapsible / expandable in my HTML for which I am using Bootstrap accordions. The above I am using the +/- switch. For example, the first time all accordions are closed and have + icons, but when I click on any to open and the icon has to be changed to (-). Now the problem with the above typescript code is that when I click on any of the accordion, all other accordion icons change to a (-) icon as well. I need to find a way to bind the click event to the specific one I clicked. I'm not sure what these are the correct words and how to explain, but in others I need a scope limit or, as I said, bind a click event to that particular click element. Here is my 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>

      

+3


source to share


1 answer


I ran into this problem a couple of times. I usually use some sort of index to keep track of which accordion the user clicked / opened and used this hint to toggle icons.

I created this simple Plunker demo . See what you are looking for :)

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;
    }

  }
}

      

Template:

<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>

      

+3


source







All Articles