问题
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