How can I select an element in a component template?

后端 未结 12 2590
挽巷
挽巷 2020-11-21 06:56

Does anybody know how to get hold of an element defined in a component template? Polymer makes it really easy with the $ and $$.

I was just

12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-21 07:02

    Note: This doesn't apply to Angular 6 and above as ElementRef became ElementRef with T denoting the type of nativeElement.

    I would like to add that if you are using ElementRef, as recommended by all answers, then you will immediately encounter the problem that ElementRef has an awful type declaration that looks like

    export declare class ElementRef {
      nativeElement: any;
    }
    

    this is stupid in a browser environment where nativeElement is an HTMLElement.

    To workaround this you can use the following technique

    import {Inject, ElementRef as ErrorProneElementRef} from '@angular/core';
    
    interface ElementRef {
      nativeElement: HTMLElement;
    }
    
    @Component({...}) export class MyComponent {
      constructor(@Inject(ErrorProneElementRef) readonly elementRef: ElementRef) { }
    }
    

提交回复
热议问题