检测指令中的输入值何时更改 [英] Detect when input value changed in directive

查看:29
本文介绍了检测指令中的输入值何时更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图检测指令中输入的何时发生变化.我有以下指令:

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');
      }
    }
}

这篇关于检测指令中的输入值何时更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆