How to pass parameter to routed component

Viewed 30

On my current HTML page, there is "Preferences" option through which user will get navigated to preferences page. I want to pass 1 parameter from prev. component to navigated component. account.component.html -

        <button mat-menu-item [routerLink]="['/preferences']">
          <mat-icon ngClass="material-icons-outlined">home</mat-icon>
          <span>Preferences</span>
        </button>

I want to pass accountNumber from this html to preferences.component.ts

2 Answers

I think I have a solution for you. Either you can pass a variable or you can pass a value.
To pass a variable you can use [routerLink]="['/preferences', username]"

<button mat-menu-item  [routerLink]="['/preferences', username]">
          <mat-icon ngClass="material-icons-outlined">home</mat-icon>
          <span>Preferences</span>
</button>


To Pass a value you can try => routerLink="/preferences/nick"

<button mat-menu-item routerLink="/preferences/nick">
          <mat-icon ngClass="material-icons-outlined">home</mat-icon>
          <span>Preferences</span>
</button>

In your preferences you have receive value or parameter like below=>

 username: string;
 constructor(private route: ActivatedRoute) {}
 ngOnInit() {
    // snapshot way
    console.log('thing', this.route.snapshot.params.username);

    // observable way
    this.route.paramMap.subscribe(params => {
      console.log(params.get('username'));
      this.username = params.get('username');
    }

Note: Please check the link of Stackblitz Demo.

Assuming your router is set up to receive parameters, and that foo holds the parameter you wish to pass:

<button mat-menu-item routerLink="preferences/{{ foo }}">

Check your code that uses @angular/router to set up the router: where the path is set for preferences, update it to add the parameter. If the parameter were to be named bar:

path: 'preferences/:bar'

On your preferences page, access the bar parameter:

import { ActivatedRoute } from '@angular/router';

 constructor(
    private activatedRoute: ActivatedRoute
 ) { }

ngOnInit() {
  this.bar = this.activatedRoute.snapshot.paramMap.get('bar');
}
Related