Chinedu
Chinedu

Reputation: 111

ERROR Error: Uncaught (in promise): Error: NG04002: Cannot match any routes. URL Segment: 'search'

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 class="form-inline my-2 my-lg-0">
    <input #searchInput  id="courseSearch"
    class="form-control mr-sm-2"  type="search" placeholder="Search an exercise" aria-label="Search">
    <a routerLink="/search/{{searchInput.value}}"
    role="button" class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</a>
</div>

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

Upvotes: 1

Views: 25755

Answers (2)

Kennedy Oliveira
Kennedy Oliveira

Reputation: 11

I solve the problem. It's happining becouse i was using "import { RouterModule } from '@angular/router'" on my app-rounting.module.ts, but i wasn't importing it in app.module.ts After i import and reference it on "imports', work just fine.

Upvotes: 1

Chris Hamilton
Chris Hamilton

Reputation: 10954

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

Upvotes: 1

Related Questions