Bwizard
Bwizard

Reputation: 1023

Angular click event inside another click event

I have the following setup in my page

angular click inside a click

When I click the main box for a division it becomes selected then the department and teams are updated in the tabs on the right. However I also want to click the edit icon to edit the name of the division.

Because the edit click event is inside the select division click event both events are being triggered when I click on edit.

What would be the solution to this? How do I click the edit button and only trigger that event without triggering the select division event? Do I have to move it outside the html then relative position it? Is there a better way?

<div class="divisionList">
   <div *ngFor="let division of filteredDivisions" (click)="selectDivision(division)"
       <form [formGroup]="formDivision" fxLayout="row" class="divisionForm">
           <h4 *ngIf="!isDivisionNameBeingEdited(division)">{{division.name}}</h4>
              <input matInput #editTitle (change)="submit()"
                  *ngIf="isDivisionNameBeingEdited(division)" class="mrmd titleInput"
                    id="title2" formControlName="division" />
            <div fxFlex></div>
            <mat-icon (click)="editDivisionName(division)">edit</mat-icon>
        </form>
    </div>
</div>
                                   

Upvotes: 1

Views: 2091

Answers (1)

peinearydevelopment
peinearydevelopment

Reputation: 11474

This the way click events are handled in JavaScript. They 'bubble' or propagate up through the parent elements. You'll need to handle the event and explicitly tell it to not propagate up the chain of elements.

<div class="divisionList">
   <div *ngFor="let division of filteredDivisions" (click)="selectDivision(division)"
       <form [formGroup]="formDivision" fxLayout="row" class="divisionForm">
           <h4 *ngIf="!isDivisionNameBeingEdited(division)">{{division.name}}</h4>
              <input matInput #editTitle (change)="submit()"
                  *ngIf="isDivisionNameBeingEdited(division)" class="mrmd titleInput"
                    id="title2" formControlName="division" />
            <div fxFlex></div>
            <mat-icon (click)="editDivisionName($event, division)">edit</mat-icon>
        </form>
    </div>
</div>

in .ts file

editDivisionName($event: MouseEvent, division) {
    $event.stopPropagation();
}

StackBlitz demonstration

Upvotes: 3

Related Questions