[英]Pass a component from child to a parent directive in angular 2
這是我的父組件:
@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文檔,但無法弄清楚有關將組件注入頂層選擇器的任何信息。
一種實現方法是使用您在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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.