问题
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']);
}
回答1:
You could use the (selectedTabChange)
event. Check 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']);
}
回答2:
You need to publish the event as an @Output
from you md-tab
component. 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 that event in the 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;
}
}
Heres a working plunker that demonstrates the concept
回答3:
You can use ngKeypress ( Angular Documentation here) into any HTML tag. For example:
<anyHtmlTag ng-keypress="yourFunction($event)">
yourFunction(evt){
if(evt.code === "Tab"){
//Do your stuff
}
}
来源:https://stackoverflow.com/questions/42059151/angular-2-how-to-watch-for-tab-changes