I believe the answer to this is "no", but is there a method/service in Angular where I can pass in a component's root DOM node (e.g. <foo-component>
) and receive the component instance (e.g. FooComponent
)?
I couldn't find an associated SO post on this.
Example:
<foo-component id="foo"></foo-component>
const fooElement: HTMLElement = document.getElementById('foo');
const fooInstance: FooComponent = getInstanceFromElement(fooElement);
Is there a method in Angular like getInstanceFromElement
?
Edit:
I can't use ViewChild
... I'm looking for a global service I can use. Suppose I am not invoking this method from the component class. I'm well acquainted with ViewChild
/ContentChild
and they are not what I'm looking for. Suppose I am in a globally injected service and am trying to do something like the following:
class MyService {
constructor() {}
getInstanceFromElement(element: HTMLElement): Component<T> {
// Is there some special helper service I can use here?
}
}
Getting ElementRef in Component Class Create a template reference variable for the element in the component/directive. Use the template variable to inject the element into component class using the ViewChild or ViewChildren.
You can get a handle to the DOM element via ElementRef by injecting it into your component's constructor: constructor(private myElement: ElementRef) { ... }
Add a template reference variable to the component HTML element. Import @ViewChild decorator from @angular/core in component ts file. Use ViewChild decorator to access template reference variable inside the component.
Angular ElementRef is a wrapper around a native element inside of a View. It's simply a class that wraps native DOM elements in the browser and allows you to work with the DOM by providing the nativeElement object which exposes all the methods and properties of the native elements.
Try like this:
Working Demo
Template:
<foo-component #foo></foo-component>
TS:
@ViewChild('foo', { static: false }) fooComponent: FooComponent;
ngAfterViewInit() {
console.log(this.fooComponent)
}
Yes, there is. @ViewChild()
was the right hint here. Let me give you an example:
@ViewChild('editorStepsDomElements', { static: false, read: ElementRef }) fooComponentDomElement: ElementRef;
@ViewChild('fooComponent', { static: false, read: FooComponent }) fooComponent: FooComponent;
So basically you can define in the ViewChild()
what you want to get. Just set the read
parameter to either ElementRef
(for getting the DOM element), or to the respective component you want to get.
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