xi ha ti no
xi ha ti no

Reputation: 91

Use route parameters in Angular 4 with ID is String

How to use route parameters with ID is String?

{path: 'param/:id', component: MyComponent}

let id = this.route.snapshot.params['id'];
Any idea

Blockquote

Upvotes: 3

Views: 6194

Answers (2)

Vlad B.
Vlad B.

Reputation: 2937

In the component you can use this code to transform from string into number:

 constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.route.paramMap
      .subscribe((params: ParamMap) => {
        let id = +params.get('id'); // This line converts id from string into num
      });
  }

Upvotes: 1

SpaceFozzy
SpaceFozzy

Reputation: 2808

Using the route snapshot to get the id query parameter as you've shown should give you a string. If you want to implicitly convert that string to a number so you can use it in a route parameter for navigation, you can prefix the variable with a +:

// (+) converts string 'id' to a number
let id = +this.route.snapshot.params['id'];

Then:

this.router.navigate(['/example', id]);

Check out this example of getting the query param in the documentation https://angular.io/guide/router#snapshot-the-no-observable-alternative.

Upvotes: 8

Related Questions