How to access the nativeElement of a Component in Angular4?

前端 未结 3 1709
星月不相逢
星月不相逢 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:59

    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

提交回复
热议问题