Home > Software engineering >  ERROR Error: Uncaught (in promise): Error: NG04002: Cannot match any routes. URL Segment: 'sear
ERROR Error: Uncaught (in promise): Error: NG04002: Cannot match any routes. URL Segment: 'sear

Time:12-21

My apologies having to ask this question seeing such similar questions, but non neither seems similar nor provides solution to my case. My route definition:

const routes: Routes=[
  
  {path: 'category/:categoryName/:id', component: DateComponent},
  {path: 'exam/:categoryName/:examYear/:categoryId', component: SubjectNameComponent},
  {path: "question/:categoryId/:subjectName/:examYear", component: SubjectComponent},
  {path: 'search/:keyword', component: SearchComponent}
]

Any other route is working fine except {path: 'search/:keyword', component: SearchComponent} with the view component:

<div >
    <input #searchInput  id="courseSearch"
      type="search" placeholder="Search an exercise" aria-label="Search">
    <a routerLink="/search/{{searchInput.value}}"
    role="button"  type="submit">Search</a>
</div>

What am I really doing wrong? I'll appreciate any clarification please.

CodePudding user response:

From the RouterLink docs: https://angular.io/api/router/RouterLink#description

For a dynamic link, pass an array of path segments, followed by the params for each segment. For example, ['/team', teamId, 'user', userName, {details: true}] generates a link to /team/11/user/bob;details=true.

So change your routerLink to:

<a
  [routerLink]="['/search', searchInput.value]"
  ...
  >Search</a
>

Through my testing, using the input reference directly seems to be a bit buggy, it works better to link a property with [(ngModel)].

  <input
    [(ngModel)]="searchInput"
  />
  <a
    [routerLink]="['search', searchInput]"
    >Search</a
  >
export class MyComponent {
  searchInput = '';
}

Demo: https://stackblitz.com/edit/angular-ivy-pbfkse?file=src/app/search/search.component.ts

  • Related