我正在开发一个带有ASP.NET Core 2.0和Visual Studio 2017 Angular的Web应用程序模板的Angular 2应用程序。从Angular 2的onChange事件中获取选定的值
我不知道如何在用户更改选择时从select中获取选定值。
这是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>
这是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;
}
这是什么产生:
<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>
这是角度的版本(ng --version
):
_ _ ____ _ ___
/\ _ __ __ _ _ _| | __ _ _ __ /___| | |_ _|
/? \ | '_ \/_` | | | | |/ _` | '__| | | | | | |
/___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
@angular/cli: 1.4.4
node: 6.11.3
os: win32 x64
这是由控制器返回的JSON:
[
{
"value": 1,
"name": "China"
},
{
"value": 2,
"name": "Korea"
},
{
"value": 3,
"name": "European"
}
]
在控制台我得到:
selected law: China .
似乎值为空。
如何获得选定的值?我认为我在定义select时犯了一些错误,但是我发现了很多使用相同语法的示例。
顺便说一下,我发现如何从这SO answer做到这一点。
你试过(其他城市)=“lawChanges($事件)来获取值 –
@UshmaJoshi我抄这个答案,HTTPS: //sackoverflow.com/a/35055235/68571,做到这一点 – VansFannel