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

suman
  • 57
  • 8

1 Answers1

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.. :)

Ganesh
  • 5,808
  • 2
  • 21
  • 41
  • 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 Jun 05 '21 at 12:11
  • 1
    @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: https://angular.io/guide/lifecycle-hooks#peek-a-boo – thecOdemOnkey Jun 05 '21 at 13:31
  • @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. – Ganesh Jun 05 '21 at 15:22