Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create (click) event on MatTab Material

I dynamically loop thru tabs and i would like to add a (click) event on to be able to load different options when i select tab.

Isn't it possible to have an event (click) event on ? I tried with (selectChange) on but then i cannot get hold of bank.id from my loop when creating tabs.

Isn't it possible to add simple click event on dynamically created tabs??

    <mat-tab-group>   <mat-tab label="All transactions">     <mat-list>       <mat-list-item *ngFor="let bank of banks">         <h4 mat-line>{{bank.fullName}}</h4>       </mat-list-item>     </mat-list>   </mat-tab>   <mat-tab *ngFor="let bank of banks" (click)="fetchAccounts(bank.id)" label="{{bank.fullName}}">      <mat-list>        <mat-list-item *ngFor="let account of accounts">         <h4 mat-line>{{bank2.fullName}}</h4>       </mat-list-item>     </mat-list>   </mat-tab>   <!-- <mat-tab label="Test Bank" disabled>     No content   </mat-tab> -->  </mat-tab-group> 
like image 688
MrWeiland Avatar asked Jan 29 '18 17:01

MrWeiland


2 Answers

Isn't it possible to add simple click event on dynamically created tabs? - no i think, it isn't possible, but you can use (selectedTabChange) on <mat-tab-group> as:

<mat-tab-group (selectedTabChange)="yourFn($event)"> 

The event-Object holds an index, so you can do something like this:

yourFn($event){     this.fetchAccounts(this.banks[$event.index].id) } 

Example: https://stackblitz.com/edit/angular-xurhan

like image 87
enno.void Avatar answered Sep 20 '22 14:09

enno.void


I don't have the same problem as you had. All I needed was a simple click event on a mat-tab. I change the route on a click event but the click event did not bind to the tab. I did some research and what you can do is create a custom label on which you can put the click event. For example...

<mat-tab>     <ng-template mat-tab-label>         <span (click)="onClick()">Custom label</span>     </ng-template> </mat-tab> 

This will work if you create the tab dynamically. To expand on your example...

<mat-tab *ngFor="let i of [1, 2, 3]">     <ng-template mat-tab-label>         <span (click)="onClick()">Custom label {{i}}</span>     </ng-template> </mat-tab> 

The only problem I had was with the css for the span. It doesn't have any padding so you actually have to click on the span itself to make the event work. If you click outside it but within the tab, the tab is going to change but the event won't fire.

To fix that, make the padding bigger on this span. For example,

.custom-label { padding: 15px 0 15px 0; }

This one, for example worked for me but there was still room on the left and right side that the click didn't wan't to fire. I din't solve that one.

like image 28
Mario Škrlec Avatar answered Sep 17 '22 14:09

Mario Škrlec