const APP_ROUTES: RouterConfig = [
{
path: 'app/home',
component: HomeComponent,
data: {
name: 'Home'
}
}
]
If I have route configuration shown as above how do I access its data
property from some directive.
@Directive({
name: 'hello'
})
class HelloDirective {
@Input('routerLink') link: string[];
ngOnInit() {
//HOW CAN I GET ROUTE AND ITS DATA FROM PATH/URL ???
//const magicallyGrabbedRoute = pleaseGiveMeMyRouteFrom(this.link);
//const myData = magicallyGrabbedRoute.data;
}
}
<a hello [routerLink]="['app/home']"> Go Home </a>
In hello
directive how can I get route configuration for the routerLink
attribute's value ?
The Router-Outlet is a directive that's available from the router library where the Router inserts the component that gets matched based on the current browser's URL. You can add multiple outlets in your Angular application which enables you to implement advanced routing scenarios.
Router service needs to be explicitly provided in angular module to use it in another component via DI. You can chain multiple pipe in a single expression along with “async” pipe.
ActivatedRoutelink. Provides access to information about a route associated with a component that is loaded in an outlet. Use to traverse the RouterState tree and extract information from nodes.
(RC6):You need to import:
import { ActivatedRoute } from '@angular/router';
Then in your constructor:
constructor(private route: ActivatedRoute) { }
The class should implements OnInit
this way:
ngOnInit() {
const myData = this.route.snapshot.data['name'];
}
This is in case your URL is not dynamic. If dynamic you should use an observer and not snapshot.
p.s. for parents of parents just use: this.route.snapshot.parent.data['name']
You can subscribe on route parameters by putting it inside your Component class. & have private route: ActivatedRoute
in constructor
this.sub = this.route
.params //.data //--> use data to retrieve route data
.subscribe(params => {
console.log(params['id']);
});
You could also use this.route.snapshot.data
to retrieve passed data in route defination.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With