DEV Community

Shane McGowan
Shane McGowan

Posted on • Edited on

9 1

Angular - How to pass arrays via Query Parameters

This is a quick guide on how to pass an array of values via query string in Angular. This is working in Angular 9+ as of 13/04/2020 but will most likely work just fine for any version from Angular 2+.

In the example below we will create an array of values in ComponentA and pass them to ComponentB via navigation. This method will work for a direct navigation to ComponentB via a link and also via programmatic navigation with the Angular router.

The short version is: JSON.stringify your array and pass it as query param, thend JSON.parse it back into an array after navigation

Component A - Passing the array

export class ComponentA {

  // We need access to the Angular router object to navigate programatically
  constructor(private router: Router){}

  navigateWithArray(): void {
    // Create our query parameters object
    const queryParams: any = {};
    // Create our array of values we want to pass as a query parameter
    const arrayOfValues = ['a','b','c','d'];

    // Add the array of values to the query parameter as a JSON string
    queryParams.myArray = JSON.stringify(arrayOfVAlues);

    // Create our 'NaviationExtras' object which is expected by the Angular Router
    const navigationExtras: NavigationExtras = {
      queryParams
    };

    // Navigate to component B
    this.router.navigate(['/componentB'], navigationExtras);
  }

}
Enter fullscreen mode Exit fullscreen mode

Component B - parsing the array

export class ComponentB {
  // Where we will be storing the values we get from the query string
  arrayOfValues: Array<string>;

  // We need use the ActivatedRoute object to get access 
  // to information about the current route
  constructor(private activatedRoute: ActivatedRoute){

    // Get the query string value from our route
    const myArray = this.activatedRoute.snapshot.queryParamMap.get('myArray');

    // If the value is null, create a new array and store it
    // Else parse the JSON string we sent into an array
    if (myArray === null) {
      this.arrayOfValues = new Array<string>();
    } else {
      this.arrayOfValues = JSON.parse(myArray));
    }
  }

}
Enter fullscreen mode Exit fullscreen mode

Enjoy

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (5)

Collapse
 
quedicesebas profile image
Sebastián Rojas Ricaurte

No need for that. Just use:

this.router.navigate(["/componentB"], {
queryParams: { myArray: arrayOfValues },
});

And then:

const myArray = this.activatedRoute.snapshot.queryParams.myArray

Collapse
 
ramki profile image
Ramakrishna Gottipat

Thank you for the tutorial..!!

How do we define router path if we pass array of values with query param?

const routes: Routes = [
{ path: 'componentb/:ids', component: componentb }
];

It is working fine if i pass array of parameters like below , With query param i am getting Cannot match any routes error.

const arrayOfValues = ['a','b','c','d'];
const ids = JSON.stringify(arrayOfValues);
this.router.navigate(['/componentb', ids])

Collapse
 
shane profile image
Shane McGowan

You are confusing route params with query params.

/componentb/:ids will only match on /componentb/1 etc but not /componentb.
In this scenario :ids is a ROUTE param, you need a query param.

You will need to change the route to

const routes: Routes = [
{ path: 'componentb', component: componentb }
];
Enter fullscreen mode Exit fullscreen mode

and then navigate as follows

this.router.navigate(
    ['/componentb'],
    { queryParams: { ids:  ids} }
  );
Enter fullscreen mode Exit fullscreen mode

This uses query params. The url will be like this /componentb?ids=['a','b','c','d']

Collapse
 
brunelakodo1 profile image
Brunel Akodo

Great tutorial ! Thanks

Collapse
 
shane profile image
Shane McGowan

You are most welcome friend

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay