繁体   English   中英

选择选项卡时运行功能-Angular2 + NativeScript

[英]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()。

您在这里可以使用的选择很少,

  1. 在每个组件中注入Router并订阅更改,并在该组件的路由匹配时执行您的功能。
  2. 在服务中声明一个BehaviorSubject ,您可以将其注入任何组件。 onSelectedIndexChanged将所选索引更新到该BehaviorSubject 如果给定索引匹配,则子组件可以订阅此BehaviorSubject并调用适当的函数。
  3. ngrx可以使这一过程变得更加简单。
  4. 您甚至可以将AppComponent / TabView注入子组件构造函数中,并侦听每个组件级别的索引更改。
  5. 您可以使用InjectoronSelectedIndexChanged事件上获取组件的实例。

我相信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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM