角度2:从Component访问元素,getDocumentById不起作用 [英] Angular 2: access an element from the Component, getDocumentById doesn't work

查看:94
本文介绍了角度2:从Component访问元素,getDocumentById不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Angular 2组件,我想在其中检索元素div <div id ="myId">通过其ID.我尝试在组件(TypeScript)中执行document.getElementById("myId"),但是出现错误:找不到名称文档".我看到在其他帖子中我们可以使用@ViewChild做类似的事情,但是我看不到如何将它与div结合使用,有什么主意吗?

解决方案

您可以通过添加

组件

  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);
    }
  }

此博客文章卡拉·埃里克森(Karl Erickson)撰写的一本非常好的书,因为它熟悉Angular的方法来完成这种事情.

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?

解决方案

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.

这篇关于角度2:从Component访问元素,getDocumentById不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆