问题
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