0

I have a component that routes to another component passing some conditional parameters

This the code that defines the routing:

redirect(topicname : string){
    alert(topicname)
    this.router.navigate(['/chapters'], { queryParams: { topic: topicname } });
  }

And on the Chapters.component.ts file I have defined:

export class ChapterstemplComponent implements OnInit {
  topic : string;
  constructor( private route : ActivatedRoute) { 
    this.topic= this.route.snapshot.params.topic;
    alert( this.route.snapshot)
  }

But this.topic does not receive any value. I want to use it in my HTML file of chapters.component. NOTE: The alert messages confirm that 'topicname' was sent well in the first snippet But in the second snippet, the route did not receive any parameters Here is the image for the same:

1st/sending alert: enter image description here

2nd/receiving alert: enter image description here

1 Answer 1

1

We can get query params with the help of paramMap

Try to do something like below, which will get the params in subscription of queryParams of ActivatedRoute.

ngOnInit() {
 this.route.queryParams.subscribe(params => {
    this.topic = params['topic'];
  });
}

You can also read more about routing in detail here: navigate-to-other-page

Happy Coding.. :)

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

3 Comments

Wow, thanks ! your detailed post clarified my doubt would you please help with another thing... What the difference between doing thing this subscription of parameters inside constructor and inside ngOnit... Itried and both working.. I am new to angular please help!
@suman This is only a timing issue. You can do both since they get called both only once. I would go with ngOnInit. see also: angular.io/guide/lifecycle-hooks#peek-a-boo
@suman first difference is constuctor is from regular typescript special method where as ngOnInit() is life cycle method of angular which will be called after component variables and methods initialisation. So it’s recommended to use ngOnInit() for bindings and api calls.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.