![](/img/trans.png)
[英]Is it possible to prevent moving the cursor to the start of an input field when type changes?
[英]Prevent Angular 2 from applying changes when input field gets edited
我使用插值將變量綁定到輸入字段(變量的值在輸入字段中反映)。 只要數據庫中的相應值發生更改,變量就會在后台自動更新。
我想阻止Angular將變量的更改應用於用戶當前正在編輯此字段的輸入字段。 否則,將覆蓋用戶的編輯。
(換句話說:我希望Angular在更新值之前檢查輸入字段當前是否使用ng-pristine標記而不是ng-dirty。)
實現這一目標最容易的原因是什么?
想法:不應該可以實現一個等於ngModel的指令,但檢查在應用該值之前是否設置了類ng-dirty?
最佳解決方案:有一個指令,它可以像ngModel那樣進行雙向數據綁定。 如果未為視圖設置“ng-dirty”標志,則該指令將模型中的更改應用於視圖。 如果視圖失去焦點(如果模糊事件被觸發),該指令將視圖中的更改應用於模型。
我可以看到這樣做的一種方法是創建一個注入NgModel
的指令。 您可以使用它來寫入視圖(在本例中為輸入),並根據需要寫入模型。 您還可以檢查模型是否是原始的而不是臟的。 例如
import { Directive, OnInit, OnDestroy, Self } from '@angular/core';
import { NgModel } from '@angular/forms';
@Directive({
selector: '[updateInput][ngModel]'
})
export class UpdateDirective implements OnInit, OnDestroy {
private interval: any;
constructor(@Self() private model: NgModel) {}
ngOnInit() {
let counter = 0;
this.interval = setInterval(() => {
console.log(`pristine: ${this.model.pristine}, dirty: ${this.model.dirty}`);
if (this.model.pristine && !this.model.dirty) {
counter += 2;
this.model.valueAccessor.writeValue(`It's been ${counter} seconds...`);
// the model will not be initially updated until the first editing by the user.
// If you want the model updated when you write to the input, call the following.
// Or comment it out if you don't want this behavior.
this.model.viewToModelUpdate(`It's been ${counter} seconds...`);
} else {
clearInterval(this.interval);
}
}, 2000);
}
ngOnDestroy() {
if (this.interval) {
clearInterval(this.interval);
}
}
}
這是一個Plunker 。
注意:此指令的選擇器不是很好。 這只是一個POC。 如果您想要一個更准確的選擇器來處理所有用例,您可能想要查看用於DefaultControlValueAccessor
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.