本文介绍了检测指令中输入值何时更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试检测指令中输入的值何时更改.我有以下指令:
I'm trying to detect when the value of an input changed in a directive. I have the following directive:
import { ElementRef, Directive, Renderer} from '@angular/core';
@Directive({
selector: '[number]',
host: {"(input)": 'onInputChange($event)'}
})
export class Number {
constructor(private element: ElementRef, private renderer: Renderer){
}
onInputChange(event){
console.log('test');
}
}
此伪指令中的问题是它仅在有输入时检测,而在值以编程方式更改时则不检测.我使用对数形式,有时使用patchValue()
函数设置值.我该怎么做才能触发变更功能?
The problem in this directive is that it detects only when there is an input and not when the value changes programatically. I use reacive form and sometimes I set the value with the patchValue()
function. How can I do so the change function gets triggered?
推荐答案
您需要将输入属性设置为input
,然后使用ngOnChanges
挂钩确定输入属性何时更改.
You need to make an input property of input
and then use the ngOnChanges
hook to tell when the input property changes.
@Directive({
selector: '[number]'
})
export class NumberDirective implements OnChanges {
@Input() public number: any;
@Input() public input: any;
ngOnChanges(changes: SimpleChanges){
if(changes.input){
console.log('input changed');
}
}
}
这篇关于检测指令中输入值何时更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!