How do I transfer the array to the routing parameter?

Issue

*I’m making a angular project (version 6+).
I want to transfer array parameter, using routing.
*

const routes: Routes = [

  {
    path: 'books',
    component: BookComponent
  }
  ,
  {
    path: 'books/:id',
    component: BookDetailComponent
  },

...

Solution

There are two ways you can use,

Method 1:

HTML

<a routerLinkActive="active" [routerLink]="['/home', userIDs.join()]">Home</a>

TS:

userIDs: Array<number> = [1, 3, 4];

Home component typescript:

export class HomeViewComponent implements OnInit {
  userIDs: Array<number> = [];

  constructor(private router: ActivatedRoute)   { }

  ngOnInit() {
    this.router.params.subscribe(params => {
      this.userIDs = params['ids'].split(',');
    });
  }    
}

Router Module:

 path: 'home/:ids', component: HomeViewComponent }

Method 2 (Using queryParams):

You don’t need to add anything into router module as we are doing in above method.

HTML

<a routerLinkActive="active" [routerLink]="['/home']" [queryParams]="{ids: userIDs}">Home</a> 

TS

userIDs: Array<number> = [1, 3, 4];

Home component typescript:

export class HomeViewComponent implements OnInit {
  userIDs: Array<number> = [];

  constructor(private router: ActivatedRoute)   { }

  ngOnInit() {
    this.router.queryParams.subscribe(p => {
        this.userIDs = p.ids;
    }); 
  }
}

Answered By – Jitendra G2

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.