[英]Angular2 ngModel change binding on Input type=“number”
我有一個數字類型輸入,當我嘗試使用onChange事件更改值時,它不起作用。
我已嘗試相同的文本輸入,它的工作完美。
<input
type="number"
[(ngModel)]="element.value"
(change)="onChange($event)"
>
export class NumFieldComponent {
@Input() index;
@Input() element; //element.value = 0
onChange($event){
var confirm = confirm("Are you sure about this?")
if(confirm){
//True, accept the value
} else {
this.element.value = 0;
//Failed, set the input back to 0
}
}
}
我是Angular2的新手,所以我在這里缺少什么?
PS。 我看到類似的問題,輸入采取bool
更改為單向綁定對我有用,如果用戶也取消,則更輕松不觸發更改(注意我仍然必須按照您的意見手動更新DOM):
<input
type="number"
[ngModel]="element.value" // one way binding
(change)="onChange($event)"
>
export class NumFieldComponent {
@Input() index;
@Input() element; //element.value = 0
onChange($event){
var confirm = confirm("Are you sure about this?")
if(confirm){
this.element.value = $event.target.value
} else {
$event.target.value = 0;
//Failed, set the input back to 0
}
}
}
沒試過,但可能會奏效
export class NumFieldComponent {
@Input() index;
@Input() element; //element.value = 0
constructor(cdRef:ChangeDetectorRef) {}
onChange($event){
var confirm = confirm("Are you sure about this?")
if(confirm){
//True, accept the value
} else {
this.element.value = 0;
this.cdRef.detectChanges(); // <<<=== added
//Failed, set the input back to 0
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.