我有一个数字类型输入,当我尝试使用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。我看到类似的问题与输入采取bools
答案 0 :(得分:1)
更改为单向绑定对我有用,如果用户也取消,则不要触发更改(注意我仍然必须按照您的意见手动更新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
}
}
}
答案 1 :(得分: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
}
}
}