5
votes

Is it possible to cast back ElementRef to a component.
I have a situation where I have in my hand the nativeElement and I need to cast it to a component. Have a look at the console.log, I want to extract the name, Can I cast it back? Thanks https://stackblitz.com/edit/angular-8aoq7f?file=src%2Fapp%2Fapp.component.ts

@Component({
  selector: 'my-app',
  template: `<sub-component [name]="'test'"></sub-component>`,
})
export class AppComponent {
 constructor(private ref : ElementRef){
    console.log((<SubComponent>this.ref.nativeElement).name); //<--- .name is undefined
 }
}

@Component({
  selector: 'sub-component',
  template: `<div>{{name}}</div>`,
})
export class SubComponent  {
  @Input() name : string
}
3

3 Answers

4
votes

You dont' have to cast an element to a component. Just use viewchild

import { Component,Input,ElementRef,ViewChild, AfterViewInit } from '@angular/core';

@Component({
  selector: 'sub-component',
  template: `<div>{{name}}</div>`,
})
export class SubComponent  {
  @Input() name : string
}

@Component({
  selector: 'my-app',
  template: `<sub-component [name]="'test'"></sub-component>`,
})
export class AppComponent implements AfterViewInit {

@ViewChild(SubComponent) private subComponent: SubComponent;

 constructor(){}

 ngAfterViewInit() {
   console.log(this.subComponent.name); // No longer undefined
 }
}

working example https://stackblitz.com/edit/angular-axtulh?file=src/app/app.component.ts

3
votes

answer to

i'm in directive and getting elementref, so i can not use viewchild, any suggestion?

can be found here https://github.com/angular/angular/issues/8277.

...
    constructor(
         @Host() @Self() @Optional() public hostCheckboxComponent : MdlCheckboxComponent
        ,@Host() @Self() @Optional() public hostSliderComponent   : MdlSliderComponent
    ){
                if(this.hostCheckboxComponent) {
                       console.log("host is a checkbox");
                } else if(this.hostSliderComponent) {
                       console.log("host is a slider");
                }
         }
...

In your case you can only use @Host() @Self() public myComponent : MyComponent

0
votes

I'm late to the party but I had the same need. It turns out there is a ng globals that contains helper functions:

ng.getComponent<T>(element: Element): T | null

https://angular.io/api/core/global/ngGetComponent

this ng is stored in the window object.

window.ng.getComponent(myElem) as MySampleComponent;