How to access the nativeElement of a Component in Angular4?

Solution 1:

If you need the ElementRef of a component, you can't use a template variable. If the element is a component, you'll get the component instance instead. A template variable only returns ElementRef for plain HTML elements.

To get ElementRef of a component, you need to use @ViewChild()

@ViewChild('chartContainer', { read: ElementRef }) myChartContainer:ElementRef;

and then pass it along with

[chartContainer]="myChartContainer"

I would make the input a setter

 private _chartContainer:ElementRef;
 @Input() 
 set chartContainer(value: ElementRef) {
   this._chartContainer = value;
   console.log(this.chartContainer);
   console.log(this.chartContainer.nativeElement);
 }

but ngOnInit works as well Plunker example

Solution 2:

The problem is that if you define a template reference on the element that Angular views as a host element of the component, you will get a reference to the component instance. Here:

<... chartContainer]="chartContainer" #chartContainer></div>

chartContainer will point to the instance of the BarChartComponent and that is why nativeElement is undefined.

To get elementRef of the host element, you don't need any bindings or lifecycle hooks, just inject the element into the constructor:

export class BarChartComponent implements OnInit {
   constructor(element: ElementRef) {
        console.log(element.nativeElement);
   }

Solution 3:

As others said, you get the Component's reference when you try to reference it with the @ViewChild('templateId') element; property. But that's totally fine, because we can reference the nativeElement of the child component in its constructor and make it publicly available from the outside components:

  // Child component
  nativeElement: HTMLElement;

  constructor(element: ElementRef) {
    this.nativeElement = element.nativeElement;
  }
  // Parent component:
 
  @ViewChild('childId') element; // element.nativeElement works now