Invoke native element method with Angular 6

The useful method invokeElementMethod() has been removed from the new Renderer v3 in the upcoming version 6 of Angular. What does it mean? For example it is now harder to invoke focus() on input field or create custom native event, which bubbles up. The motivation of the Angular team is that this method has not been used internally, therefore they have removed it. I don’t think this was the best solution, because this method has been used by many.

So now when you need to focus some input field, you need to write up your own renderer service. It makes the things more complicated without obvious benefit. Or am I missing something?

You can create your own injectable renderer service like this

import { Injectable, PLATFORM_ID, Inject, ElementRef } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

@Injectable()
// Based on https://github.com/angular/angular/issues/13818#issuecomment-372276031
// and source code of the old Renderer V1
export class CustomRenderer {

  constructor(
    @Inject(PLATFORM_ID) private platformId: Object
  ) { }

  invokeElementMethod(eleRef: ElementRef, method: string, args: any[]) {
    if (isPlatformBrowser(this.platformId)) {
      let element = eleRef.nativeElement;
      element[method].apply(element, args);
    }
  }
}

You can use it to create native DOM elements which will bubble-up. That is sometimes easier, than having chain of EventEmmiters across a tree of components. You can create custom event like this

@Component({
  selector: 'app-demo',
  templateUrl: './demo.component.html',
  styleUrls: ['./demo.component.scss']
})
export class DemoComponent implements OnInit {
 constructor(private elRef: ElementRef, private customRenderer: CustomRenderer) { }

 this.customRenderer.invokeElementMethod(
  this.elRef, 
  'dispatchEvent', 
  [new CustomEvent('nameOfCustomEvent', {bubbles: true})]
 );
}

Hope this helps someone