Detect when input value changed in directive

后端 未结 4 1801
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-03 17:48

I\'m trying to detect when the value of an input changed in a directive. I have the following directive:

         


        
相关标签:
4条回答
  • 2021-02-03 18:11

    There is a better way to detect when an Input property changes, it's considered a best practice and it's also used in the *ngIf implementation.

    You just need to postpone the keyword set after Input(), in this way you combine the @Input() decorator with a setter, and it gets called all the times the value changes.

    _rows: number;
    @Input() set rows(value: number) {
      if (this.value < 0) {
        console.error('The number of rows must be positive');
        this._rows = 2;
        return;
      }
    
      this._rows = value;
    }
    

    If you want to compare the new value with the previous value, you must store the variable in a class property, and retrieve it the second time the method got called:

    private previousValue: any = T;
    
    @Input() set myInputName(value: T) {
      console.log(`Previous value was: ${this.previousValue}`);
      console.log(`New value is: ${value}`);
      this.previousValue = value;  
    }
    
    0 讨论(0)
  • 2021-02-03 18:15

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

    Plunkr

    Stackblitz

    0 讨论(0)
  • 2021-02-03 18:24

    You can also use HostListener. For more information about HostListener, you can go through this link. Here is the code.

    import {Directive, ElementRef, HostListener} from '@angular/core';
    
    
    @Directive({
           selector: '[number]'
     })
    
    export class NumberDirective {
    
        @Input() public number: any;
        @Input() public input: any;
    
        constructor(private el: ElementRef) {}
    
        @HostListener('change') ngOnChanges() {
            console.log('test');
        }
    
    }
    
    0 讨论(0)
  • 2021-02-03 18:27

    As of Angular 9+ I can verify that the snippet below is the correct solution. It's best to avoid ngOnChanges whenever possible for several reasons and use the correct host listener event instead. The below example will get the current input value on keyup. You can easily customize this code snippet for whatever you need on an input directive.

      @Directive({
          selector: '[appMyDirective]',
      })
      export class MyDirective {
        // Add whatever event you want to track here
        @HostListener('keyup', ['$event']) public onKeyup(event: KeyboardEvent): void {
          const value = (event.target as HTMLInputElement).value;
          console.log(value);
        }
      }

    0 讨论(0)
提交回复
热议问题