Valentyn Chernysh
Valentyn Chernysh

Reputation: 113

Angular Router.navigate to child route with queryParams

Can't navigate to child route with queryParams by Angular.Router.navigate

Аlready tried:

this.router.navigateByUrl('/desktop/search?q=folder'));

this.router.navigate(['desktop', 'search'], { queryParams: {q: 'folder'} });

this.router.navigate(['desktop/search'], { queryParams: {q: 'folder'} });

my routes:

{
    path: 'desktop',
    component: FavoritesPageComponent,
    children: [
      { path: 'desktop-admin', component: DesktopAdminComponent },
      { path: 'favorites', component: FavoritesBodyMainComponent },
      { path: 'sessions', component: SessionsComponent },
      { path: 'search', component: FavoritesBodySearchComponent },
      { path: 'shared_with_me', component: FavoritesBodySharedComponent },
      { path: 'recycle', component: FavoritesBodyRecycleComponent } 
    ] 
}

when i try to navigate to 'desktop/search?q=folder' i've got the following error:

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'desktop/search%3Bq%3D%25D0%25BF%25D0%25B0%25D0%25BF%25D0%25BA%25D0%25B0'

What's wrong? Is there a way to use child routes with normal queryParams like

.../desktop/search?q=folder

this.route.queryParams.subscribe(params => {
   console.log('params['q']: ', params['q']);
});

Upvotes: 7

Views: 25090

Answers (4)

Abdul
Abdul

Reputation: 1208

Version: Angular: 14.1.0

Nothing above is working for me. Here is my answer.

Routes Config:

const routes: Routes = [
  { path: '', component: WelcomeComponent },
  { path: 'welcome', component: WelcomeComponent },
  {
    path: 'home', component: HomeComponent, canActivate: [AuthGuard],
    children: [{
      path: 'test1', component: Test1Component
    },
    {
      path: 'test2', component: Test2Component
    },
    {
      path: 'attendance', component: AttendanceComponent
    }]
  },
  { path: '**', component: WelcomeComponent }
];

Navigating to that route. Here we should be careful. In the above answers few people used navigateByUrl. navigateByUrl will not work in child routes.

The correct way of routing in child nodes is below

  navigate(path: string) {
    let cMName = this.cName + ": navigate. ";
    console.log(`In ${cMName} giving path: ${path}`);

    this.router.navigate([path], { relativeTo: this.activatedRoute, queryParams: { classCode: 'GRADE_1' } })

  }

Retrieving the query parm on the other end is as follows

    this.activatedRoute.paramMap.subscribe(params => {
      console.log(`In ${cMName}. In activated route block`);

      this.activatedRoute.queryParamMap.forEach(qParm => {
        if (qParm.has('classCode')) {
          let classCode = qParm.get('classCode');
          console.log(`${cMName} Selected Class Code: ${classCode}`);
          if (classCode != null)
            this.getStudentsFor(classCode);
          else
            console.log(`In ${cMName} empty class code recived`);
        }


      });
}

Upvotes: 0

Valentyn Chernysh
Valentyn Chernysh

Reputation: 113

Sry, all works fine. It was my typo in code.. :) So, here is correct way to use queryParams:

this.router.navigate(['desktop', 'search'], { queryParams: {q: 'folder'} });

I don't wanna use UrlParams, because i will have a lot of params on this page and url like:

.../foo/bar/foo1/bar1/foo2/bar2/.../foo-x/bar-x

will not look beauty. Thnx all for help

Upvotes: 4

Morteza Ebrahimi
Morteza Ebrahimi

Reputation: 760

Look at this example:

1- Declaring route parameters:

// app.routing.ts    
export const routes: Routes = [
      { path: '', redirectTo: 'product-list', pathMatch: 'full' },
      { path: 'product-list', component: ProductList },
      { path: 'product-details/:id', component: ProductDetails }
    ];

to see the product details page for product with ID 10, you must use the following URL:

localhost:4200/product-details/10 // it's not this -> /product-details?id:10

2- Linking to routes with parameters:

<a [routerLink]="['/product-details', 10 or variable name]">
 title
</a>

or

<a (click)="goToProductDetails($event,10)">
     title
</a>

// into component.ts
goToProductDetails(e,id) {
  e.preventDefault();
  this.router.navigate(['/product-details', id]);
}

3- Reading route parameters:

// into component.ts

 constructor(private route: ActivatedRoute) {}

 ngOnInit() {
    this.route.params.subscribe(params => {
       this.id = +params['id']; 
    });
  }

I hope this helps you.

Upvotes: 5

user3804427
user3804427

Reputation: 442

router params in angular are separated by ';' not '&'. You must define route with parameter:

{ path: 'hero/:id', component: HeroDetailComponent }

then you can use this example for navigate:

this.router.navigate(['/heroes', { id: heroId }]);

As you can see router.navigate have one parameter and its object:

['/heroes', { id: heroId }]

Check this for more details

Upvotes: 1

Related Questions