Angular 2: access an element from the Component, g

2019-02-05 14:41发布

I have an Angular 2 component where I want to retrieve an element div <div id ="myId"> by its id. I try doing: document.getElementById("myId") in my component (TypeScript), but i get an error: "cannot find name document". I see that in other posts we can do something similar using @ViewChild, however I don't see how we can use this with a div, any ideas?

2条回答
祖国的老花朵
2楼-- · 2019-02-05 14:58

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);
   }
}
查看更多
干净又极端
3楼-- · 2019-02-05 15:07

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.

查看更多
登录 后发表回答