5

Hello I'm writing an angular 15 application with angular material.

I use the new mat-tab (not the legacy) component to create tabs in my page, and i want in the tab title to have a close button.

so in the component i created removeTab function:

removeTab(index: number) {
    this.tabs.splice(index, 1);
  }

and in the template I did the following:

<mat-tab-group>
  <mat-tab *ngFor="let tab of tabs; let index = index">
    <ng-template mat-tab-label>
      {{index}}
      <button (click)="removeTab(index)" mat-icon-button><mat-icon>close</mat-icon></button>
    </ng-template>
...

the problem is that when i hover on the close button it doesn't show that it's clickable and when i click on it just clicks on the tab itself, the events don't propagate to the close button.

how can I resolve such a thing ?

ufk
  • 30,912
  • 70
  • 235
  • 386

2 Answers2

3

found the answer at Can't click button in tab header/label in Angular 15

i need to add pointer-events:auto style to the button, and than use $event.stopPropagation() so it won't move to a different tab if i close it while focusing on some other tab.

so the button code is now:

  <button style="pointer-events: auto"  (click)="removeTab(index);$event.stopPropagation()" mat-icon-button><mat-icon>close</mat-icon></button>
ufk
  • 30,912
  • 70
  • 235
  • 386
0

When you click on the cross button, the event is bubbled to the parent tab element, to stop it use event.stopPropagation();

Make these changes:

removeTab(event: PointerEvent, index: number) {
    console.log(event);
    event.stopPropagation();
    this.tabs.splice(index, 1);
  }

And,

<button (click)="removeTab($event, index)" mat-icon-button>
        <mat-icon>close</mat-icon>
      </button>

You can refer to this link: Reference

Hirdesh Vishwdewa
  • 2,334
  • 1
  • 19
  • 33
  • event propagation is not the issue, only the tab gets the click event, the button doesn't get the click event. angular15 has reimplemented angular material components and this example uses angular5 – ufk Dec 13 '22 at 17:04