I'm developing an Angular 2 application with ASP.NET Core 2.0 and the Visual Studio 2017 Angular's Web application template.
I don't know how to get the selected value from a select when the user changes the selection.
This is the law.component.html
:
<p *ngIf="!laws"><em>Loading...</em></p>
Legislaciones:
<select #l (change)="lawChanges(l.value)">
<option></option>
<option *ngFor="let law of laws" [ngValue]="law">{{law.name}}</option>
</select>
This is the law.component.ts
:
import { Component, Inject, Output, EventEmitter } from '@angular/core';
import { Http, RequestOptions, Headers } from '@angular/http';
@Component({
selector: 'law',
templateUrl: './law.component.html'
})
export class LawComponent {
public laws: Law[];
@Output()
change: EventEmitter<number> = new EventEmitter<number>();
constructor(private http: Http,
@Inject('BASE_URL') private baseUrl: string) {
http.get(baseUrl + 'api/Law').subscribe(result => {
this.laws = result.json() as Law[];
}, error => console.error(error));
}
lawChanges(selectedLaw: Law) {
console.log("selected law: " + selectedLaw.value + " " + selectedLaw.name + ".");
this.change.emit(selectedLaw.value);
}
}
interface Law {
value: number;
name: string;
}
At this what it generates:
<select>
<option></option><!--bindings={"ng-reflect-ng-for-of": "[object Object],[object Object"}-->
<option ng-reflect-ng-value="1">China</option>
<option ng-reflect-ng-value="2">Korea</option>
<option ng-reflect-ng-value="3">European</option>
</select>
This is the angular's version (ng --version
):
_ _ ____ _ ___
/ \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|
/ ? \ | '_ \ / _` | | | | |/ _` | '__| | | | | | |
/ ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
@angular/cli: 1.4.4
node: 6.11.3
os: win32 x64
This is the JSON returned by the controller:
[
{
"value": 1,
"name": "China"
},
{
"value": 2,
"name": "Korea"
},
{
"value": 3,
"name": "European"
}
]
At the console I get:
selected law: China .
It seems that value is empty.
How can I get the selected value? I think I'm doing something wrong when I define the select but I have found a lot of examples with the same syntax.
By the way, I've found how to do it from this SO answer.