[英]Angular Material 5: how to call a function when a tab is selected (clicked)?
[英]Run function when tab is selected - Angular2+NativeScript
我熟悉Angular,但是我剛開始學習NativeScript。 我有一個使用NativeScript庫中的選項卡模板的選項卡界面。 我想在選擇選項卡時運行一個功能,但無法確定它。
這是app.component.html:
<TabView [(ngModel)]="tabSelectedIndex" androidTabsPosition="bottom" (selectedIndexChanged)="onSelectedIndexChanged($event)">
<page-router-outlet *tabItem="{title: 'Home', iconSource: getIconSource('home')}" name="homeTab">
</page-router-outlet>
<page-router-outlet *tabItem="{title: 'Away', iconSource: getIconSource('browse')}" name="awayTab">
</page-router-outlet>
<page-router-outlet *tabItem="{title: 'Matchup', iconSource: getIconSource('search')}" name="matchupTab">
</page-router-outlet>
</TabView>
我到目前為止在matchup.component.ts中還沒有任何東西,因為我還不能弄清楚。 雖然是這樣:
import { Component, OnInit } from "@angular/core";
import { DataService } from "../core/data.service";
import { ActivatedRoute } from "@angular/router";
@Component({
selector: "Matchup",
moduleId: module.id,
templateUrl: "./matchup.component.html"
})
export class MatchupComponent implements OnInit {
constructor(
private data: DataService,
private route: ActivatedRoute
) { }
homeTeam: any;
awayTeam: any;
isVisible = false;
ngOnInit(): void {
}
getTeams() {
this.homeTeam = this.data.getHomeTeam();
this.awayTeam = this.data.getAwayTeam();
}
}
選擇選項卡后,我希望能夠調用getTeams()。
您在這里可以使用的選擇很少,
Router
並訂閱更改,並在該組件的路由匹配時執行您的功能。 BehaviorSubject
,您可以將其注入任何組件。 在onSelectedIndexChanged
將所選索引更新到該BehaviorSubject
。 如果給定索引匹配,則子組件可以訂閱此BehaviorSubject
並調用適當的函數。 ngrx
可以使這一過程變得更加簡單。 onSelectedIndexChanged
事件上獲取組件的實例。 我相信TabView
只會保留活動的標簽。 這意味着每次您選擇一個新選項卡時,該選項卡的ngAfterViewInit
都會被調用。
export class MatchupComponent implements AfterViewInit {
ngAfterViewInit() {
this.homeTeam = this.data.getHomeTeam();
this.awayTeam = this.data.getAwayTeam();
}
}
但是,根據您的數據模型,直接鏈接到服務可能更有利。
export class MatchupComponent {
get homeTeam(): Team {
return this.data.getHomeTeam();
}
get awayTeam(): Team {
return this.data.getAwayTeam();
}
}
是否會在app.component中使用onSelectedIndexChanged
這樣的工作?
onSelectedIndexChanged(args: SelectedIndexChangedEventData) {
if (args.newIndex == 0)
this.homeComponent.init();
else if (args.newIndex == 1)
this.awayComponent.init();
else if (args.newIndex == 2)
this.matchUpComponent.init();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.