本文介绍了如何将输入值作为参数传递给 Angular 中的路由器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我相信我正在尝试做的事情是微不足道的,但我已经尝试了很多不同的事情并且无法弄清楚.
I believe what I'm trying to do is trivial, but I've tried many different things and can't figure it out.
我有两个组件,SearchComponent
和 DetailsComponent
用于显示搜索结果.
I have two components, SearchComponent
and DetailsComponent
that displays search results.
路由模块:
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()
?
How do I get the name
input's value and pass it as a parameter to onSearch()
?
推荐答案
如果你想获得 name 的值,你可以像这样简单地为输入字段分配一个引用 #name.您需要执行以下操作:
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>
希望有帮助!
这篇关于如何将输入值作为参数传递给 Angular 中的路由器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!