2016-07-22 109 views
1

我有一個簡單的Angular 2組件,它有一個選擇下拉列表,它具有與對象屬性的雙向綁定以及綁定到操作該對象的方法的更改事件。 這裏是組件選擇下拉onChange和ngModel問題

import {Component} from '@angular/core' 

@Component({ 
selector: 'my-app', 
providers: [], 
template: ` 
    <div> 
    <h2>Hello {{name}}</h2> 

    <select (change)="save()" [(ngModel)]="testObject.selectVal"> 
     <option [selected]="testObject.selectVal=='Value 1'">Value 1</option> 
     <option [selected]="testObject.selectVal=='Value 2'">Value 2</option> 
     <option [selected]="testObject.selectVal=='Value 3'">Value 3</option> 
    </select> 

</div> 
`, 
directives: [] 
}) 
export class App { 

testObject:any; 

constructor() { 
    this.name = 'Angular2 (Release Candidate!)' 

    this.testObject = { 
    selectVal : "Value 2" 
    } 

} 

save(){ 

    alert(this.testObject.selectVal); 

} 
} 

當我改變了選擇,就應該警惕當前所選選項的值,而是它總是顯示選擇下拉菜單中的最後一個值。我有一種感覺,ngModel更新和change觸發器之間存在競爭狀態,因爲我試圖在save方法中的警報提前延遲並且它似乎正常工作。

爲了演示它更好,我已經安裝了一個演示文稿here

回答

2

你不需要

[selected]="testObject.selectVal=='Value 1'" 

的項目從通過選擇相應的值testObject.selectVal選擇通過[(ngModel)]

如果testObject.selectVal不包含Value 1一個,Value 2,或Value 3,然後用(用於字符串值)

<option [value]="someVal">Value 1</option> 

或其他值如ob JECT

<option [ngValue]="someVal">Value 1</option> 
+0

好點,但主要問題仍然存在。該值仍未按時更新。 – xmaestro

+0

使用'(ngModelChange)=「save()」'而不是 –

+0

這也沒有幫助 – xmaestro

0

可以作爲替代,因爲警報事件燒製的第一比ngModelChange

public save(item){ 
 
\t alert(item); 
 
\t }
<select (change)="save(item.value)" #item [(ngModel)]="testObject.selectVal"> 
 
     <option [selected]="testObject.selectVal=='Value 1'">Value 1</option> 
 
     <option [selected]="testObject.selectVal=='Value 2'">Value 2</option> 
 
     <option [selected]="testObject.selectVal=='Value 3'">Value 3</option> 
 
    </select>

0

我有(change)處理程序和模型綁定中相同的競爭條件使用。使用(ngModelChange)爲我解決了它(documentation link)。

含義,你的情況:

import {Component} from '@angular/core' 

@Component({ 
selector: 'my-app', 
providers: [], 
template: ` 
    <div> 
    <h2>Hello {{name}}</h2> 

    <select (ngModelChange)="save()" [(ngModel)]="testObject.selectVal"> 
     <option [selected]="testObject.selectVal=='Value 1'">Value 1</option> 
     <option [selected]="testObject.selectVal=='Value 2'">Value 2</option> 
     <option [selected]="testObject.selectVal=='Value 3'">Value 3</option> 
    </select> 

</div> 
`, 
directives: [] 
}) 
export class App { 

testObject:any; 

constructor() { 
    this.name = 'Angular2 (Release Candidate!)' 

    this.testObject = { 
    selectVal : "Value 2" 
    } 

} 

save(){ 

    alert(this.testObject.selectVal); 

} 
} 

希望這有助於你。