Home > Software design >  add a close button to mat-tab-label in angular-material 15
add a close button to mat-tab-label in angular-material 15

Time:12-14

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 ?

CodePudding user response:

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

CodePudding user response:

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