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
}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With