Skip to content Skip to sidebar Skip to footer

Add Parameter To Angular 2 Route From Component Without Navigating

With my current code I am attempting to do deep linking within my Accordion component. By navigating to dev.local/#/accordion and then clicking on an accordion title, I want to upd

Solution 1:

If the Aux Routes don't help, you can try my solution I used for a smiliar problem:

  1. Build a RootAccordionComponent. Set a selector for your AccordionComponent and use it as a tag in the RootAccordionComponent template (e.g. ). Also place a somewhere in this template. For RootAccordionComponent you use "path: '/accordion/...'" RouteConfig.

  2. (If not already done) build a AccordionService with a tabId attribute.
  3. Build a TabIdAccordianComponent with an empty template. Use "path: '/accordion/:tab'" for it as RouteConfig. Now the only thing the component does, is to fetch the tabId from RouteParams and save it to the AccordionService.
  4. When initializing your AccordianComponent, get the tabId from the AccordionService.

That way you can get the tabId when your AccordianComponent is initilized if someone goes directly to the url with an tabId, but it won't reload if the user clicks on an Accordian.

See this Plunker for a working example: http://plnkr.co/edit/5HEgIUZGRP3Cfqh6LvzA?p=preview

If you launch the preview in a separate window you can also see the routes. E.g. if you load "http://run.plnkr.co/WOpQaPkFafJ7uU8Y/#/accordion/2" the selected Accordion will be set to 2.

Hope this helps, although it is not the cleanest solution.

RouteConfig to get to AccordionRoot:

@RouteConfig([
  {path:'/accordion/...', name: 'AccordionRoot', component: AccordionRootComponent},
])
export class AppComponent { }

The actual AccordionRootComponent:

@Component({
    template: `
      <router-outlet></router-outlet>
      <accordion-component></accordion-component>`,
    directives: [ROUTER_DIRECTIVES, AccordionComponent]
})

@RouteConfig([
    { path: '/:tabId', name: 'AccordionTab', component: TabIdAccordionComponent, useAsDefault: true}
])
export class AccordionRootComponent { }

The TabIdAccordionComponent:

@Component({
    template: ''
})

export classTabIdAccordionComponent{

  constructor(private routeParams: RouteParams, private accordionService: AccordionService){
    let tabId = +this.routeParams.get("tabId");
    this.accordionService.tabId = tabId;
  }
}

The AccordionComponent making use of the tabId from the service: export class AccordionComponent implements OnInit { constructor(private accordionService: AccordionService){} selectedAccordionId: number;

ngOnInit(){
    this.setSelectedAccordion(this.accordionService.tabId);
  }

  setSelectedAccordion(tabId: number){this.selectedAccordionId = tabId;}

}

Post a Comment for "Add Parameter To Angular 2 Route From Component Without Navigating"