Angular 5 : How to get parent component routing parameter in child component?

大兔子大兔子 提交于 2019-12-11 02:26:27

问题


Here is add-new-folder.component, this component is child component of folder.component when I route on add-new-folder.component from folder.component that time I want folder.component parameter userid in its child component, I tried below code but i get console NaN how to get parent component parameter in child component kindly help me?

add-new-folder.component.ts

constructor(private route : ActivatedRoute,private router : Router){}  

ngOnInit() {     
  this.route.parent.params.subscribe(params => {
    const parentRouteId = +params['userid'];
    console.log(parentRouteId);
  });
}

folder.component.html

<mat-icon [routerLink]="['/addNewFolders/',userid]">folder</mat-icon>

app-routing.module.ts

const routes: Routes = [
 { path: 'folder/:userid', component : FolderComponent,
   children: [
     { path: 'addNewFolders/:userid', component : AddNewFolderComponent },
   ]},
];

回答1:


try this approach. first create two common methods in any common file which will be used to get and set your id.

let parameterId : string=" ";
export function setParameterId(id) {
  parameterId = id;
}

export function getParameterId() {
  return parameterId;
}

before navigate to child component, first call this.setParameterId(id); and after navigate to child component get that id by calling this.getParameterId()




回答2:


Add the below attribute your route link to preserve the params.

 <a [routerLink]="['/base/addNewFolders/',userid]" queryParamsHandling="preserve"></a>

You just have to preserve your queryParams so that you get the parameters to the child components too



来源:https://stackoverflow.com/questions/53493549/angular-5-how-to-get-parent-component-routing-parameter-in-child-component

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