How can I select an element in a component template?

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

    Mimimum example for quick usage:

    import { Component, ElementRef, ViewChild} from '@angular/core';
    
    @Component({
      selector: 'my-app',
      template:
      `
      
      `,
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      @ViewChild('inputEl') inputEl:ElementRef; 
    
      ngAfterViewInit() {
        console.log(this.inputEl);
      }
    }
    
    1. Put a template reference variable on the DOM element of interest. In our example this is the #inputEl on the tag.
    2. In our component class inject the DOM element via the @ViewChild decorator
    3. Access the element in the ngAfterViewInit lifecycle hook.

    Note:

    If you want to manipulate the DOM elements use the Renderer2 API instead of accessing the elements directly. Permitting direct access to the DOM can make your application more vulnerable to XSS attacks

提交回复
热议问题