![](/img/trans.png)
[英]How to detect in Angular 8 whether a value in angular is changed by user or a method call has changed it
[英]In Angular 6, How to check whether formControl value has changed in each focusout?
我在子組件中有一個@Input變量 - 度量單位為英寸。 我的表單有 2 個輸入文本控件 - 1.英尺2.英寸我將 @Input 轉換為英尺和英寸。 僅當表單中的值發生更改時,在focusOut上,它才應將值發送給父級。
真正的問題是,我的焦點每次都會發出,而沒有檢查值是否發生了變化。
情況是,
我們可以使用NgOnChanges
來比較@Input
prop 以前的值和當前值。 如果當前值與先前值不同,我們會做一些事情。
export class AppComponent implements OnChanges {
@Input() textValue;
ngOnChanges(changes: SimpleChanges) {
const text: SimpleChange = changes.textValue;
if (text.currentValue !== undefined && text.previousValue !== undefined) {
console.log('prev value: ', text.previousValue);
console.log('current value: ', text.currentValue);
if (text.previousValue !== text.currentValue) {
console.log('new different value!');
// do something here with text.currentValue
}
}
}
}
或者使用Hostlistener
監聽focusout
事件以捕獲事件發出的值。 將事件值表單輸入與子組件值中的先前值進行比較。
@HostListener('focusout', ["$event.target.value"])
onFocusOut(inputValue) {
console.log('input value on focus out', inputValue);
if (this.textValue !== inputValue) {
console.log('new different value!');
// do something here with inputValue
}
}
我更喜歡ngOnChanges
方法。 它使閱讀更清晰,避免了一些額外的偵聽器,我們可以將SimpleChanges
obj 用於其他輸入。 但是,使用OnChanges
更改檢測僅在道具更改時運行。 如果出於某種原因您總是想使用focusOut
運行這些檢查(無論輸入更改如何),那么Hostlistener
將是我的示例的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.