Some tab content

Angular 2 How to "Monitor" Tab Changes

I have:

<md-tab-group color="primary"> <md-tab label=""> <h1>Some tab content</h1> </md-tab> <md-tab label=""> <h1>Some more tab content</h1> <p>...</p> </md-tab> </md-tab-group> 

I need to catch an event when a specific tab is clicked and call this function inside my component:

 onLinkClick() { this.router.navigate(['contacts']); } 

I am very new to programming, especially in Angular 2. I would be grateful for any advice.

+8
angular angular-material2
source share
2 answers

You can use the event (selectedTabChange) . Check out the Material2 # tabs .

Template:

 <mat-tab-group color="primary" (selectedTabChange)="onLinkClick($event)"> ... </mat-tab-group> 

Component :

 import { MatTabChangeEvent } from '@angular/material'; // ... onLinkClick(event: MatTabChangeEvent) { console.log('event => ', event); console.log('index => ', event.index); console.log('tab => ', event.tab); this.router.navigate(['contacts']); } 
+29
source share

You need to post the event as @Output from you md-tab . Something like:

 import { EventEmitter, Output, Input, Component } from '@angular/core'; @Component({ selector: 'tab', template: ` <button (click)="clicked()">{{ name }}</button> `, styles: [` `] }) export class TabComponent { @Input() name = 'replaceme'; @Output() tabClicked = new EventEmitter<null>(); clicked() { this.tabClicked.emit(); } } 

Then you consume this event in md-tab-group , something like this:

 import { Component } from '@angular/core'; @Component({ selector: 'tab-group', template: ` <!--<tab *ngFor="let tab of tabs" [name]="tab"></tab>--> <tab *ngFor="let tab of tabs" [name]="tab" (tabClicked)="tabChanged(tab)"></tab> <div> {{ selectedTab }} </div> `, styles: [` `] }) export class TabGroupComponent { private tabs = ['foo', 'bar']; private selectedTab = this.tabs[0]; onInit() { this.selectedTab = this.tabs[0]; } tabChanged(tab) { this.selectedTab = tab; } } 

The working plunker demonstrates the concept.

0
source share

All Articles