【问题标题】:How to pass input value as parameter to router in Angular如何将输入值作为参数传递给Angular中的路由器
【发布时间】:2018-07-07 01:00:50
【问题描述】:

我相信我正在尝试做的事情是微不足道的,但我尝试了很多不同的事情并且无法弄清楚。

我有两个组件,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()

【问题讨论】:

  • 您使用的是什么类型的表格?模型驱动还是模板驱动?

标签: javascript angular routing


【解决方案1】:

如果您想获取 name 的值,您可以简单地为输入字段分配一个引用,例如 #name。以下是您需要做的:

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>

希望对您有所帮助!

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-09-21
  • 1970-01-01
  • 2017-04-01
  • 2018-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多