角度对象-将选定的值传递给另一个变量

时间:2019-03-24 09:20:58

标签: angular

我试图将类型编号的变量设置为对象的选定值,但不了解如何设置它。

我想知道所选猫的年龄。我希望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

3 个答案:

答案 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)

Take a look at this demo code

<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
}