将一个组件从子组件传递给角度为2的父组指令

时间:2016-06-03 12:40:14

标签: angular angular2-routing angular2-directives

这是我的父组件:

@Component({
    selector : "app",
    template : '        
            <app-header></app-header>
            <top-navigation></top-navigation>
            <router-outlet></router-outlet>    
            <app-footer></app-footer>                
            <page-js-rersources></page-js-rersources>',
    directives : [AppHeader, AppFooter]
})
@RouteConfig([
    {path: '/', name: "UserHome", component: LandingPage, useAsDefault: true },
    {path: '/login', name: "Login", component: LoginSignUp },
    {path: '/splash', name: "SplashBuildup", component: Splash },
    {path: '/home', name: "HomeBuildup", component: Home }        
])
export class UserLayoutBuildUp{

    constructor(){

    }

}

这是我的孩子组成部分:

@Component({
    templateUrl: "splash.tmpl.htm",
})
export class Splash{

}

这是我的顶级导航组件:

@Component({
    selector: "top-navigation",
    templateUrl: "topNavigation.tmpl.htm"
})
export class TopNavigation{

}

我想在启动路由器组件激活 UserLayoutBuildUp 组件的顶部导航选择器时包含我的顶部导航组件。

我已经尝试过Angular 2文档,但无法弄清楚将组件注入顶级选择器的任何事情。

1 个答案:

答案 0 :(得分:2)

一种方法是使用您在bootstrap注入的服务。然后使用路由器生命周期挂钩来控制此服务。这将导致类似这样的事情:

未经测试的代码..

ConfigurationService

export class ConfigurationService { //or whatever name you'd like

    public showTopNavigation: boolean = false;  
    //... use it for other settings you might come across
}

自举

bootstrap(AppComponent, [ConfigurationService]); //And other things

UserLayoutBuildUp

@Component({
    selector : "app",
    template : `        
            <app-header></app-header>
            <top-navigation *ngIf="_configuration.showTopNavigation"></top-navigation>
            <router-outlet></router-outlet>    
            <app-footer></app-footer>                
            <page-js-rersources></page-js-rersources>`,
    directives : [AppHeader, AppFooter]
})
@RouteConfig([
    {path: '/', name: "UserHome", component: LandingPage, useAsDefault: true },
    {path: '/login', name: "Login", component: LoginSignUp },
    {path: '/splash', name: "SplashBuildup", component: Splash },
    {path: '/home', name: "HomeBuildup", component: Home }        
])
export class UserLayoutBuildUp{

    constructor(private _configuration: ConfigurationService){}

}

SplashComponent

@Component({
    templateUrl: "splash.tmpl.htm",
})
export class SplashComponent {

    constructor(private _configuration: ConfigurationService){}

    routerOnActivate() : void {
       this._configuration.showTopNavigation = true;
    }

    routerOnDeactivate() : void {
       this._configuration.showTopNavigation = false; 
    }
}
相关问题