如何在Angular中将输入值作为参数传递给路由器

时间:2018-01-28 02:11:16

标签: javascript angular routing

我相信我想要做的事情是微不足道的,但我已经尝试了许多不同的事情,无法弄明白。

我有两个组件,SearchComponentDetailsComponent,用于显示搜索结果。

路线模块:

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

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

export class AppRoutingModule {}

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>

然后在search.component.ts

export class SearchComponent implements OnInit {

constructor(private router: Router) {
}

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

如何获取name输入的值并将其作为参数传递给onSearch()

1 个答案:

答案 0 :(得分:1)

如果您想获得名称的值,您可以简单地为输入字段分配对此 <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> 的引用。这是你需要做的:

  

search.component.html

name

希望它有所帮助!