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

后端 未结 2 439
心在旅途
心在旅途 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:23

    Add Template Reference variable to the element you need access to:

    And in the component:

    class MyComponent implements AfterViewInit {
       @ViewChild('myDiv') myDiv: ElementRef;
    
       constructor() {}
    
       ngAfterViewInit() {
          console.log(this.myDiv);
       }
    }
    

提交回复
热议问题