Get ComponentRef from DOM element

前端 未结 2 749
你的背包
你的背包 2021-01-05 08:52

It has already been answered how to get the DOM element from an Angular 2 component: ComponentRef.location.nativeElement (ComponentRef.location gives the Elemen

相关标签:
2条回答
  • 2021-01-05 09:05

    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.

    0 讨论(0)
  • 2021-01-05 09:17

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

    }

    0 讨论(0)
提交回复
热议问题