2

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()?

HenryDev
  • 4,685
  • 5
  • 27
  • 64
Asalas77
  • 612
  • 4
  • 15
  • 26

1 Answers1

2

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!

HenryDev
  • 4,685
  • 5
  • 27
  • 64
  • Can you tell me how to do this for radio button group? https://pastebin.com/d3bhhD1p here on line 12 instead of `'Feronis' ` in `onSearch()` – Asalas77 Jan 30 '18 at 15:25
  • @Asalas77 Here's a link that will solve your problem: https://stackoverflow.com/questions/31879497/angular2-radio-button-binding – HenryDev Jan 30 '18 at 17:23