62619

Detect when input value changed in directive

Question:

I'm trying to detect when the <strong>value</strong> 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'); } }

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?

Answer1:

You need to make an input property of input and then use the ngOnChanges hook to tell when the input property changes.

<pre class="lang-js prettyprint-override">@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'); } } }

<a href="http://plnkr.co/edit/Ygd9CDWg2OxG6n88zRqD" rel="nofollow">Plunkr</a>

Answer2:

You can also use HostListener. For more information about HostListener, you can go through <a href="https://angular.io/guide/attribute-directives" rel="nofollow">this link</a>. 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'); } }

Answer3:

There is a better way to use this result, used for example in the *ngIf Angular <a href="https://github.com/angular/angular/blob/1a44a0b4a87767236f6eea07deca5e4d8789572f/packages/common/src/directives/ng_if.ts#L113" rel="nofollow">source code</a>.

You can combine an @Input() with a setter. When the input changes, the setter is called again.

@Input() set numberOfWheels(wheels: number) { if(wheels === 2) { console.log("It's a bike!"); } else if(wheels === 4) { console.log("It's a car!"); } else { console.log("I don't know what it is :("); } }

You can save the previous value in the Directive property in order to use it later and compare it with the new value:

private previousValue: any = null; @Input() set myInputName(value: any) { console.log(`Previous value is: ${this.previousValue}`); console.log(`New value is: ${value}`); this.previousValue = value; }

Recommend

  • pattern matching of the form: Option{..}
  • give role when a user add reaction Discord.py
  • OSX sed newlines - why conversion of whitespace to newlines works, but newlines are not converted to
  • Redmine can't generate secret token
  • Can I switch the 'connected' user within an sql script that is sourced by mysql?
  • Firebase suddenly reports invalid signature
  • Hyperlink to Outlook Attachment
  • Enable CORS on Tomcat 8.0.30
  • Tensorflow crash using tf.train.Saver() with GPU
  • Auto send email based on the time and email address in database
  • Defer unused CSS
  • Extracting a small subset of data from XMLs
  • How to display content depending on dropdown menue user selection
  • Set initial vuetify v-select value
  • Splitting ReportLab table across PDF page (side by side)?
  • Facebook Error (#200) The user hasn't authorized the application to perform this action (PHP)
  • Building JavaFX 2.0 App on Mac, deploying on Windows
  • Julia 1.0 UndefVarError - Scope of Variable
  • Add checkbox dynamically using angular 2
  • How to load dynamic images in custom ListView
  • How to use array in autohotkey?
  • How to make Rss News Reader application in android …? [closed]
  • Generate and export point cloud from Project Tango
  • Wireshark Display Filter for Unique Source/Destination IP and Protocol
  • What is the difference between dynamically creating a script tag and statically embed a script tag?
  • Ajax call on Multiple selection in Select box
  • Tensorflow Dataset API restore Iterator after completing one epoch
  • Error handeling in antlr 3.0
  • JavaScript Regex to Match Boundaries of Words with diacritics
  • How to turn off notice reporting in xampp?
  • How to integrate angular2-material (alpha 8.2) with angular2-Quickstart app
  • read part of h5 dataset python
  • Cross compile glibc for arm, got undefined reference to some unwind functions
  • WPF custom control and direct content support
  • Write to .csv file with PHP (Commas in Data Error)
  • How to mutate multiple variables without repeating codes?
  • ARKit code issue {unknown error -1=ffffffffffffffff error: Task failed with exit 1}