How to access the nativeElement of a Component in Angular4?

前端 未结 3 1707
星月不相逢
星月不相逢 2020-12-16 09:31

I have two components and one with attribute selector. The child component is,

import { Component, OnInit, Input, El         


        
3条回答
  •  悲哀的现实
    2020-12-16 09:51

    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>

    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);
       }
    

提交回复
热议问题