无法访问Angular自定义指令

问题描述:

上的RouterStateSnapshot属性我正在编写自定义指令,根据激活的路由更改background-image样式属性。无法访问Angular自定义指令

为了实现此功能,我尝试达到RouterStateSnapshoturl属性,并根据url的值操作元素的样式。

我只是为了测试而登录到控制台。

这是代码。

import { Directive, Renderer } from '@angular/core'; 
import { Router, RouterState, RouterStateSnapshot } from '@angular/router'; 

@Directive({ 
    selector: '[bgImg]' 
}) 
export class BgImgDirective { 

    constructor(
    private _renderer: Renderer, 
    private _router: Router 
) { 

    var state: RouterState = this._router.routerState; 
    var stateSnapshot: RouterStateSnapshot = state.snapshot; 
    var url: any = stateSnapshot.url; 

    console.log(url); 
    } 

} 
  • console.log(url);什么也不打印到控制台。
  • url变量始终是空

这是我的根app.component模板

<div bgImg> 
    <app-navbar></app-navbar> 
    <router-outlet></router-outlet> 
</div> 
<app-footer></app-footer> 

然而

,如果我尝试console.log(this._router);

这是结果:

Console output

我要如何才能到达的url在路由器的不同状态值,并正确应用if语句来这?我是否必须使用Observables?

+1

很难说。也许你得到根路由器,而不是你真正想要的段的路由器。这取决于您的指令应用于何处。 –

+0

@GünterZöchbauer,我用app.component.html中的代码更新了我的问题 – rbenvenuto

+0

您试图让它像router.routerState而不是router.currentRouterState .. –

你可以从那里

constructor(router:Router) { 
    router.events.forEach((event) => { 
    if(event instanceof NavigationStart) { 
    } 
    // NavigationEnd 
    // NavigationCancel 
    // NavigationError 
    // RoutesRecognized 
    }); 
} 

订阅路由器事件并获取URL又见How to detect a route change in Angular 2?

answer by Günter Zöchbauer把我放在正确的方式来实现我一直在寻找。这里是代码:

import { Directive, Renderer, ElementRef } from '@angular/core'; 
import { Router, NavigationStart } from '@angular/router'; 
import 'rxjs/add/operator/filter'; 

@Directive({ 
selector: '[BgImg]' 
}) 
export class BgImgDirective { 

constructor(
private _elRef: ElementRef, 
private _renderer: Renderer, 
private _router: Router 
) { 
_router.events 
.filter(event => event instanceof NavigationStart) 
.subscribe((event: NavigationStart) => { 
    switch(event.url) { 
    case "/": 
    _renderer.setElementStyle(_elRef.nativeElement, "background-image", "url('../path/to/img')"); 
    break; 
    case "/other-page": 
    _renderer.setElementStyle(_elRef.nativeElement, "background-image", "url('../path/to/img')"); 
    break; 
    } 
    }); 
} 
}