bat7
bat7

Reputation: 866

Router link in angular 6 using query parameters

I have router link that navigate between pages and I send parameters in url using

queryParamsHandling: "merge"

In some situations I want to remove specific parameter from url but I don't want to loose all parameters.

My url look like: http://localhost:4200/school/440404?SelectedTab=1&UserName=bat7

After route I want to remove SelectedTab parameter bun not UserName Parameter.

the URL shold look like:

http://localhost:4200/school/440404?UserName=bat7

the router code is in different component,

that contains a back button that do the route, using the code behind:

this.router.navigate([], { relativeTo: this.route, queryParamsHandling: "preserve" });

Any ideas?

Upvotes: 1

Views: 1542

Answers (1)

sanjay kumar
sanjay kumar

Reputation: 858

Angular allowed two type navigation strategy one is absolute path and second is relative path.

  1. Using absolute path strategy we need to write hard code path on components level.
  2. Using relative path strategy we need to write path only route-level.

For the solution of question please follow below steps.

Steps 1: Declare routing

const routes: Routes = [
  { path: '', redirectTo: '/school', pathMatch: 'full' },
  { path: 'school', component: DashboardComponent },
  { path: 'school/:SelectedTab/:UserName', component: SchoolComponent },
];

Step 2: Declare method for go to school in your first component like below. Then You get similar url like

e.g. http://localhost:4200/school/1/sa

goToSchool() {
    let object: any = {};
    object.SelectedTab = 1;
    object.UserName = 'sa';
    this.router.navigate([object.SelectedTab, object.UserName], { relativeTo: this.route});
  }

Step 3: After then go back from school you need to modify url like below code for getting only UserName

 GoBackFromSchool() {
    this.router.navigate(['../../'], { relativeTo: this.route, queryParams: { UserName: 'sa' } });
  }

e.g. : http://localhost:4200/school?UserName=sa

Upvotes: 1

Related Questions