我试图将类型编号的变量设置为对象的选定值,但不了解如何设置它。
我想知道所选猫的年龄。我希望selectAge
是一个整数,但显示为NaN
HTML:
<select [(ngModel)]="selectedOption">
<option [ngValue]="undefined" disabled>Select An Option</option>
<option *ngFor="let o of options" [ngValue]="o.age">Name: {{o.name}}</option>
</select>
组件:
selectedOption: any;
options = [
{ name: "Neeko", age: 4},
{ name: "Gato", age: 6},
{ name: "Gatto", age: 12}
]
// This is the problem. How do I correct it?
// selectAge: number = +this.selectedOption; //NaN
答案 0 :(得分:0)
您可以在ngModelChange
指令上使用<select>
事件。当您的选择更改时,Angular将调用ngModelChange
,然后您就可以分配您的值:
HTML:
<select [(ngModel)]="selectedOption" (ngModelChange)="onValueChanged($event)">
<option [ngValue]="undefined" disabled>Select An Option</option>
<option *ngFor="let o of options" [ngValue]="o.age">Name: {{o.name}}</option>
</select>
$event
变量代表所选的选项。
export class AppComponent {
selectedOption: any;
options = [
{ name: "Neeko", age: 4},
{ name: "Gato", age: 6},
{ name: "Gatto", age: 12}
];
public onValueChanged(selected: any): void {
this.selectedOption = selected;
console.log(this.selectedOption); // should display the selected option.
}
}
答案 1 :(得分:0)
<select [(ngModel)] ="selected" name="valueCheck" (change)="valueChange($event)">
<option [ngValue]="undefined" disabled>Select Any </option>
<option *ngFor="let obj of stud"
[ngValue]="obj.age" [selected]="obj.age == selected">
{{obj.name}}
</option>
</select>
在ts
事件上使用(change)
代码
valueChange(event) {
this.selectAge = +this.selected;
}
答案 2 :(得分:0)
例如,您的selectedOption变量为Null,因此出现此错误。您可以使用ngModelChange事件来绑定它。
在您的html文件中
<select (ngModelChange) = "dataChanged($event)" [(ngModel)]="selectedOption">
<option [ngValue]="undefined" disabled>Select An Option</option>
<option *ngFor="let o of options" [ngValue]="o.age">Name: {{o.name}}</option>
</select>
Ts文件
selectAge: number = 0;
dataChanged($event){
this.selectAge = +this.selectedOption
}