How to pass input value as parameter to router in Angular

落花浮王杯 提交于 2021-02-08 09:16:21

问题


I believe what I'm trying to do is trivial, but I've tried many different things and can't figure it out.

I have two components, SearchComponent and DetailsComponent that displays search results.

A route module:

const routes: Routes = [
{ path: '', component: SearchComponent},
{ path: 'armory/:name', component: DetailsComponent}
];

@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})

export class AppRoutingModule {}

and an input in search.component.html

<form class="form-inline container-fluid">
  <input type="text" id="name" placeholder="Character name..." class="form-control">
  <button (click)="onSearch( ... <!--name should be here-->)" class="btn">
    <span class="fa fa-search"></span></button>
</form>

and then in search.component.ts:

export class SearchComponent implements OnInit {

constructor(private router: Router) {
}

onSearch(name: string) {
   this.router.navigate(['/armory', name])
}
}

How do I get the name input's value and pass it as a parameter to onSearch()?


回答1:


If you want to get the value of name you can simply assign a reference to the input field like this #name. Here's what you need to do:

search.component.html

 <form class="form-inline container-fluid">
  <input type="text" id="name" #name  placeholder="Character name..." 
  class="form-control">
  <button (click)="onSearch(name.value)" class="btn">
   <span class="fa fa-search"></span></button>
  </form>

Hope it helps!



来源:https://stackoverflow.com/questions/48482518/how-to-pass-input-value-as-parameter-to-router-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!