Angular 2 - 尝试从select中获取值时未定义

Aw3*_*ame 5 angular

我是Angular 2的新手,我遇到了这个问题.我有一个选项有3个选项,我无法获得其中一个选项的价值.

html:

<select [(ngModel)]="product_type" class="form-control" (ngModelChange)="getType()">           
        <option [ngValue]="A"><span>ALL</span></option> 
        <option [ngValue]="T"><span>Type product</span></option>
        <option [ngValue]="E"><span>Standart product</span></option>            
    </select>
Run Code Online (Sandbox Code Playgroud)

Component.ts:

 type_product:string;
/*...*/
 getType(){
   this.type_product= ""+this.type_product;
  console.log(this.type_product);

}
Run Code Online (Sandbox Code Playgroud)

当我执行它时,日志显示未定义.我做错了什么?谢谢

AJT*_*T82 5

使用[]意味着你试图绑定一个你没有的变量,所以除了事实之外,它不应该是[ngValue],它用于绑定非字符串值,它不应该[value]是,但是value.

另外,双向绑定[(ngModel)]="product_type"实际上基本上等于以下内容:

[ngModel]="product_type" (ngModelChange)="onChange($event)"  
Run Code Online (Sandbox Code Playgroud)

所以选择任一版本.

以下是您的代码的外观:

<select [ngModel]="product_type" class="form-control" (ngModelChange)="getType($event)">           
  <option value="A"><span>ALL</span></option> 
  <option value="T"><span>Type product</span></option>
  <option value="E"><span>Standard product</span></option>            
</select>
Run Code Online (Sandbox Code Playgroud)

和ts:

getType(event){
  this.product_type= ""+event;
  console.log(this.product_type);
}
Run Code Online (Sandbox Code Playgroud)

DEMO

PS,是的,正如其他人所指出的,您的命名约定不匹配:

product_type VS type_product