2017-02-06 24 views
8

mam:kątowa 2 Jak „oglądać” na zakładkę zmienia

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

muszę złapać zdarzenie, gdy dana karta jest kliknięty i wywołać tę funkcję w mojej części:

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

Jestem bardzo nowy w programowaniu, szczególnie w Angular 2. Będę wdzięczny za wszelkie porady.

Odpowiedz

29

Można użyć (selectedTabChange)zdarzenie. Sprawdź Material2#tabs.

Szablon:

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

Komponent:

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']); 
} 
+0

To dobrze, ale z zakładki nawigacji, whitout nie działa. Czy zdarzenie ma miejsce, gdy używamy dyrektywy mat-tab-nav-bar w elemencie nav? – nevradub

0

Musisz opublikować wydarzenie jako komponent od ciebie md-tab. Coś jak:

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

Następnie można konsumować to wydarzenie w md-tab-group, coś takiego:

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; 
    } 
} 

Heres a working plunker that demonstrates the concept

Powiązane problemy