angulartypescriptangular-renderer2angular-renderer

invokeElementMethod in Renderer2 angular


Context Angular project
I have the following snippet:

export class OnlyNumberDirective {
  constructor(private _el: ElementRef,private renderer:Renderer2) {
  }
  @HostListener('input', ['$event']) onInputChange(e) {
    this.renderer.invokeElementMethod(this._el.nativeElement, 'dispatchEvent', [event]);
  }
}

it uses Renderer, but it is deprecated and now we have Renderer2?
What is the alternative to invokeElementMethod method in Renderer2?


Solution

  • try this one:

    export class OnlyNumberDirective {
      constructor(private _el: ElementRef) {
      }
      @HostListener('input', ['$event']) onInputChange(e) {
        let event: Event = document.createEvent("Event");
        event.initEvent('input', true, true);
        Object.defineProperty(event, 'target', { value: this._el.nativeElement, enumerable: true });
        this._el.nativeElement.dispatchEvent(event);
      }
    }