Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 Casting back ElementRef to Component

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
}
like image 392
SexyMF Avatar asked Aug 01 '18 18:08

SexyMF


2 Answers

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

like image 106
David Anthony Acosta Avatar answered Oct 09 '22 10:10

David Anthony Acosta


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

like image 38
Tomas Bilek Avatar answered Oct 09 '22 10:10

Tomas Bilek