简体   繁体   中英

Angular click event inside another click event

I have the following setup in my page

点击内的角度点击

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>
                                   

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.stopPropogation();
}

StackBlitz demonstration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM