I'm coding a custom Directive that change the background-image style property according to the activated route.
To achieve this functionality, i try to reach the url
property of RouterStateSnapshot
, and manipulate the element's style according to url
's value.
I'm logging to the console just for test.
Here's the code.
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);
prints nothing to the console.- The
url
variable is always empty
This is my root app.component template
<div bgImg>
<app-navbar></app-navbar>
<router-outlet></router-outlet>
</div>
<app-footer></app-footer>
However
If i try console.log(this._router);
This is the result:
How can I get to the value of url
on different states of the Router, and properly apply an if statement to these? Do i have to make use of Observables?