Reputation:
Routing rules are:
const routes: Routes = [{
path: "",
component: SkeletonComponent,
children: [{
path: "dictionary",
component: DictionaryComponent,
children: [
{
path: ":dict/:code",
component: VersionsComponent
}]
}];
URL looks like:
http://localhost:4200/dictionary/Gender/5
Where Gender
is parameter: :dict
and 5
is parameter :code
.
I tried to get parameters inside component VersionsComponent
:
ngOnInit() {
console.log(this.activateRoute.snapshot.params['dict']);
console.log(this.activateRoute.snapshot.params['code']);
}
I always get undefined
Upvotes: 0
Views: 9777
Reputation: 392
The other answers that use 'subscribe' method are partially correct, but the reason you're still getting an error is that they're missing the 'get()' part, as per the Angular documentation:
https://angular.io/api/router/ParamMap
Try this:
import { Router,ActivatedRoute } from '@angular/router';
myVar
ngOnInit(): void {
this._Activatedroute.paramMap.subscribe((data) => {
this.myVar = data.get('NameOfVariable') // Put the name of whatever variable you're trying to get here
})
console.log(this.myVar)
}
And it seems you've already received help on how to pass the data from the parent, but just to round off the answer, this is how I usually do it:
<button [routerLink]="['/myLink',dataVar]"> Click Here </button>
Upvotes: 0
Reputation: 432
i think Your Routes configuration is wrong, should be like that:
const routes: Routes = [
{
path: '',
component: SkeletonComponent
},
{
path: "dictionary",
component: DictionaryComponent,
children: [{
path: ":dict/:code",
component: VersionsComponent
}]
}
];
and make sure on DictionaryComponent your using <router-outlet>
Upvotes: 0
Reputation: 19
As mentioned above go with paramMap. Please refer the stackblitz
ngOnInit() {
this.activatedRoute.paramMap.subscribe((data)=>{
console.log(data.params)
})
}
Upvotes: 0
Reputation: 1215
The most effective way (works in all scenarios) is to subscribe to Activated Route. It'll work even when you don't switch between components, and only change the parametarised portions of the URL.
this.activatedRoute.params.subscribe(
(params: Params) => {
console.log(params.dict)
}
)
If you don't subscribe to params, the code will only work when the component is loaded initially. After that, you need to leave the component for it to work again. By subscribing, you can load multiple resources without ever leaving the component.
Upvotes: 4