Angular 2: access an element from the Component, getDocumentById doesn't work

后端 未结 2 432
心在旅途
心在旅途 2020-12-29 20:05

I have an Angular 2 component where I want to retrieve an element div

by its id. I try doing: document.getElementById(\"myId\")
2条回答
  •  天命终不由人
    2020-12-29 20:31

    You can use @ViewChild with a div by adding a TemplateRef.

    Template

        

    Component

      import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
    
      @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
      })
      export class AppComponent implements AfterViewInit {
        @ViewChild('myId') myId: ElementRef;
    
        constructor() {
        }
    
        ngAfterViewInit() {
          console.log(this.myId.nativeElement);
        }
      }
    

    This blog post by Kara Erickson is a really good read for getting familiar with the Angular approach to doing things like this.

提交回复
热议问题