Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access route data from directives in angular2

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 ?

like image 232
Lekhnath Avatar asked Sep 08 '16 09:09

Lekhnath


People also ask

Which directive is used to display the component matched by routes?

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.

Which service can be used to extract route parameters inside component?

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.

What does the ActivatedRoute interface allows you to access?

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.


2 Answers

(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']

like image 89
mrgoos Avatar answered Oct 27 '22 13:10

mrgoos


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.

like image 30
Pankaj Parkar Avatar answered Oct 27 '22 12:10

Pankaj Parkar