1

Here I define the route in the angular 10 project:

const routes: Routes = [
  { path: '', component: component1},
  { path: 'myComponent/:dataId', component: component2}
];

I also have this array:

let myArr:string = ["5","4","7","2"] 

In route, I pass dataId as a parameter as you can see above but I also need to pass myArr in the route as a parameter.

My question is how to pass an array of string as a parameter in route?

2
  • 1
    maybe routerLink can help routerLink="['/myComponent/:dataId/', {arrValues:[myArr}]" I had saved this link a while ago stackblitz.com/edit/angular-jeqbbd Commented Oct 27, 2020 at 3:53
  • the array is exactly like that or u have a complex object array ? Commented Oct 27, 2020 at 4:38

2 Answers 2

2

You can pass the array as a queryParams by JSON.stringify. And use JSON.parse to get the array in target page.

    this.route.navigate(["myComponent/id"], {
      queryParams: {
        prop: JSON.stringify(myArr)
      }
    });

In the myComponent

    this.route.queryParams.subscribe(params => {
      console.log(JSON.parse(params.prop))
    })

if the myArr is a complex object array this might doesn't work as expected.

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

Comments

1

You can simply pass your array of numbers as comma separated string to your route parameter. Something like this..

<a routerLink="/myComponent/1,2,3,4,5">Second Component</a>

And you can read the parameter, from the activatedRoute service snapshot and convert it back to array of numbers. Something like this.

this.idsArr = this.activatedRoute.snapshot.params.dataId
  .split(",")
  .map(x => {
    return parseInt(x);
  });

Here is a working stackblitz example.

Comments

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.