How to Set Route params imperatively in named outlets in Angular 2

微笑、不失礼 提交于 2019-12-12 12:07:01

问题


To set imperatively a route param in a router-outler we do:

this.router.navigate(['/hero', hero.id]);

How do I imperatively set a route parameter in named outlets ?

this.router.navigate([{ outlets:{modal: 'modal/user'} }]);

Right now I concatenate string to set a route param:

this.router.navigate([{ outlets: {modal: 'modal/user' + '/' + 'this.id'} }]);

回答1:


make sure your routing file have :id in modal component like this in mine

{ path: 'component-aux/:id', component: ComponentAux, outlet: 'sidebar' }

and your calling route should be like this

id: string="any value you want to set";
this.id= input || 'not set';

|| will set default value if no value is specified

 <a [routerLink]="[{ outlets: { 'sidebar': ['component-aux', this.id] } }]">Component Aux</a>

and your aux component should be like this

import {Component} from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'component-aux',
  template: 'Component Aux'
})
export default class ComponentAux { 
  private id;
  private sub: any;
  constructor(private route: ActivatedRoute) {}

  private ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
      this.id = +params['id']; // (+) converts string 'id' to a number
      console.log(this.id);
    });
  }

  private ngOnDestroy() {
    this.sub.unsubscribe();
  }

}

here is the live plnkr link https://plnkr.co/edit/5aP6MgTRzXr5Urq5fr2J?p=preview . i hope this will help :)



来源:https://stackoverflow.com/questions/42048426/how-to-set-route-params-imperatively-in-named-outlets-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!