2

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 },
   ]},
];
8
  • Place where you call your child component ? Commented Nov 27, 2018 at 6:07
  • @RahulSwamynathan I do not understand what you want to say Commented Nov 27, 2018 at 6:11
  • You are doing it right, just remove the + from +params['userid'], I believe your parameter is not numeric. Commented Nov 27, 2018 at 6:21
  • @AshishRanjan i remove + but console prints NaN Commented Nov 27, 2018 at 6:30
  • See this link: stackblitz.com/edit/… Commented Nov 27, 2018 at 6:32

2 Answers 2

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()

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.