Textbox on changes directive

2019-01-27 05:00发布

问题:

What is the equivalent for jQuery change event on every input in Angular2? Example:

$("input").on('change', function() { 
   console.log("*"); 
});

回答1:

You can handle it using Directive as said by Igor as below

  1. create a directive using

    import { Directive, HostListener, Renderer, ElementRef } from '@angular/core';
    @Directive({
        selector: '[change]'
    })
    export class ChangeDirective{
    
        constructor(
            private renderer: Renderer,
            private el: ElementRef
        ){}
    
        @HostListener('keyup') onKeyUp() {
    
         console.log('some thing key upped')
    
        }
    }
    
  2. Import it to the main.ts

  3. Add to declarations of the module

LIVE DEMO