It has already been answered how to get the DOM element from an Angular 2 component: ComponentRef.location.nativeElement
(ComponentRef.location gives the Elemen
This could be achieved using the ElementProbe API. It is mainly intended for debugging / protractor integration, similar to element.scope()
in Angular 1.
In order to use this API, you would need to include ELEMENT_PROBE_PROVIDERS
in your bootstrap()
call. You will then be able to get any component instance by calling the global ng.probe()
.
For example, here is how you get the component instance for the current event target:
ng.probe(event.target).componentInstance
Updated Plunker showing this is action
You can see the actual implementation of the ElementProbe API Here.
I just had to do this. I was able to accomplish it by using a combination of @ViewChildren in the "parent" component class and setting a unique identifier on the "child" component itself.
So, it the parent component, you have:
@ViewChildren(YourChildComponent)
elements: QueryList<YourChildComponent>;
Then, in your child component, you do the following (note that I imported the angular2 uuid package, but you can use any mechanism for generating a unique id):
constructor(private elementRef:ElementRef) {
this.UniqueID = UUID.UUID();
this.elementRef.nativeElement.setAttribute('unique-id', this.UniqueID);
}
//and we define a public property here
UniqueID: string;
Now, you can access your children and match them up by identifier like this:
private findElementByNativeDOMObject(el: any) : YourChildComponent{
let uniqueId = el.attributes.getNamedItem('unique-id').value;
if ( ! uniqueId)
return null;
// ok, let's go through our children
return this.elements.find( x=> x.UniqueID == uniqueId);
}