Get ComponentRef from DOM element

前端 未结 2 766
你的背包
你的背包 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: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;
    

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

    }

提交回复
热议问题