Akhilesh Kumar
Akhilesh Kumar

Reputation: 9355

Accessing Select element value in angular2 gives Error

I'm using angular 2 rc4 My view is as following:

<select class="form-control" (change)="selectTestName=this.value;getChartData()">
    <option *ngFor="let st of selectTestNameList" value="{{st.selectTestName}}">{{st.selectTestName}}</option>
</select>

After change it throws following error:

TypeError: Cannot read property 'value' of undefined
    at DebugAppView._View_GeneralTrnd0._handle_change_20_0 (GeneralTrnd.template.js:367)
    at eval (eval at <anonymous> (vendor.js:25), <anonymous>:316:24)
    at eval (eval at <anonymous> (vendor.js:45), <anonymous>:278:36)
    at eval (eval at <anonymous> (vendor.js:48), <anonymous>:20:93)
    at ZoneDelegate.invoke (zone.js:323)
    at Object.onInvoke (eval at <anonymous> (vendor.js:17), <anonymous>:45:41)
    at ZoneDelegate.invoke (zone.js:322)
    at Zone.runGuarded (zone.js:230)
    at NgZoneImpl.runInnerGuarded (eval at <anonymous> (vendor.js:17), <anonymous>:78:78)
    at NgZone.runGuarded (eval at <anonymous> (vendor.js:13), <anonymous>:228:73)

Upvotes: 0

Views: 191

Answers (2)

Cybey
Cybey

Reputation: 71

Try it like this:

<select class="form-control" #selectbox (change)="selectTestName=selectbox.value;getChartData()">
  <option *ngFor="let st of selectTestNameList" value="{{st.selectTestName}}">{{st.selectTestName}}</option>
</select>

You have to assign a name to the selectbox. You can use that name to access the value.

Upvotes: 1

Maximilian Riegler
Maximilian Riegler

Reputation: 23506

Instead of this.value use $event.target.value.

<select class="form-control" (change)="selectTestName=$event.target.value;getChartData()">
    <option *ngFor="let st of selectTestNameList" value="{{st.selectTestName}}">{{st.selectTestName}}</option>
</select>

Upvotes: 2

Related Questions