Get ComponentRef Component from DOM Element

As already mentioned, how to get a DOM element from an Angular 2 component: ComponentRef.location.nativeElement (ComponentRef.location provides an ElementRef that gives direct access to the DOM).

But how to do the opposite, i.e. get a reference to ComponentRef when I only have my own DOM object?

I am in the case when I try to drag the components of Angular 2 using interactive.js. The library uses callback functions to notify which element is being dragged and which element we are trying to delete. An event object is provided, and the only useful information I found was the DOM ( target ) element.

Example:

 interact('my-component-tag').draggable({ // ... onstart: function (event:any) { var dom = event.target; // ref to the <my-component-tag> tag // How to find the Angular ComponentRef object here? } // ... }).dropzone({ // ... ondragenter: function (event:any) { var targetDom = event.relatedTarget; // targeted <my-component-tag> tag // Same question here, // to identify where we want to insert the dragged element. } // ... }); 

Plunker here

You can check the handlers in src/Interactjs.ts . Open the console to view related logs and drop the component to another. I have information about DOM elements, but instead I want Angular components, say, to access the count attribute.

Conclusions and attempts:

I found a solution for the jquery-ui-draggable plugin , but this trick does not work here, at least for the purpose of where to refuse.

There are also topics on how to embed in the DOM, talking about the DomAdapter, but I have not found any method that seems to help from the DOM to Angular.

I just thought about manually searching for my components: looping in the DOM nodes, counting to find the position, and getting the component from the list of components in the same position, but it's so ugly ...

Any advice on this is welcome. Thanks for reading!

+7
angular
source share
1 answer

This can be achieved using the ElementProbe API . It is mainly intended for debug / protractor integration, similar to element.scope() in Angular 1.

To use this API, you need to include ELEMENT_PROBE_PROVIDERS in your bootstrap() call. Then you can get any instance of the component by calling global ng.probe() .

For example, here's how you get a component instance for the current event target:

 ng.probe(event.target).componentInstance 

Updated Plunker showing this action

You can see the actual implementation of the ElementProbe API here .

+3
source share

All Articles