Get ComponentRef from DOM element

那年仲夏 提交于 2019-11-30 20:11:42

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);

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!