Reputation: 61
I am new to angular2 so trying to understand many things here. I have a select box for which I need the value to be passed to method on change (this is being tried for autocomplete). But when I use [(ngModel)], the bind is not working and is throwing an error. Would anybody know how to do this?
<select class="form-control" name="SearchBy" [(ngModel)]="SearchFor" (change)="changeSearchFor(SearchFor)">
<option value="1">Name</option>
<option value="2">ID</option>
<option value="3">SID</option>
<option value="4">Cost Center</option>
<option value="5">Manager ID</option>
<option value="6">Unit</option>
</select>
Upvotes: 1
Views: 151
Reputation: 657238
If you use ngModel
use ngModelChange
to get notified about changes. (change)="..."
is fired before SearchFor
is updated by ngModel
updated
<select class="form-control" name="SearchBy" [(ngModel)]="SearchFor" (ngModelChange)="changeSearchFor($event)">
Upvotes: 1
Reputation: 15442
If you only need to get a value in your function, then you can do it without ngModel
:
<select class="form-control" name="SearchBy" (change)="changeSearchFor($event.target.value)">
<option value="1">Name</option>
<option value="2">WWID</option>
<option value="3">IDSID</option>
<option value="4">Cost Center</option>
<option value="5">Manager WWID</option>
<option value="6">Organisational Unit</option>
</select>
if you do use ngModel
, make sure to import and add to @NgModule
's imports array FormsModule:
import {FormsModule} from '@angular/forms'
...
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ App ],
bootstrap: [ App ]
})
example plunker: https://plnkr.co/edit/PGeipOAz5kKpxO5HdTc8?p=preview
Upvotes: 0
Reputation: 3369
If you're getting the error using the ngModel directive, probably is due to you've not imported FormsModule, as the syntax seems correct to me. You need these lines in the module:
import {FormsModule} from '@angular/forms';
@NgModule({
imports: [
FormsModule
]
})
Also you don't need to pass SeachFor as a parameters as it is a variable that you're already linking in your typescript.
PD: If you're going to include autocomplete, have you considered defining a model driven form? This way you can subscribe to the form valueChanges observable and apply reactive programming to it, as it is explained in this link: https://blog.thoughtram.io/angular/2016/06/22/model-driven-forms-in-angular-2.html
Upvotes: 0