[英]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.