How can I select an element in a component template?

后端 未结 12 2198
挽巷
挽巷 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:19

    For people trying to grab the component instance inside a *ngIf or *ngSwitchCase, you can follow this trick.

    Create an init directive.

    import {
        Directive,
        EventEmitter,
        Output,
        OnInit,
        ElementRef
    } from '@angular/core';
    
    @Directive({
        selector: '[init]'
    })
    export class InitDirective implements OnInit {
        constructor(private ref: ElementRef) {}
    
        @Output() init: EventEmitter = new EventEmitter();
    
        ngOnInit() {
            this.init.emit(this.ref);
        }
    }
    

    Export your component with a name such as myComponent

    @Component({
        selector: 'wm-my-component',
        templateUrl: 'my-component.component.html',
        styleUrls: ['my-component.component.css'],
        exportAs: 'myComponent'
    })
    export class MyComponent { ... }
    

    Use this template to get the ElementRef AND MyComponent instance

    Use this code in TypeScript

    init(myComponentRef: ElementRef, myComponent: MyComponent) {
    }
    

提交回复
热议问题