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

荒凉一梦 提交于 2019-11-30 08:08:38

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

Template

    <div id ="myId" #myId>

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.

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

<div #myDiv></div>

And in the component:

class MyComponent implements AfterViewInit {
   @ViewChild('myDiv') myDiv: ElementRef;

   constructor() {}

   ngAfterViewInit() {
      console.log(this.myDiv);
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!