加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2:从Component访问一个元素,getDocumentById不起作用

发布时间:2020-12-17 08:02:47 所属栏目:安全 来源:网络整理
导读:我有一个Angular 2组件,我想要检索一个元素div div id =“myId”通过它的身份.我尝试在我的组件(TypeScript)中执行:document.getElementById(“myId”),但是我收到一个错误:“找不到名称文档”.我看到在其他帖子中我们可以使用@ViewChild做类似的事情,但我
我有一个Angular 2组件,我想要检索一个元素div
< div id =“myId”>通过它的身份.我尝试在我的组件(TypeScript)中执行:document.getElementById(“myId”),但是我收到一个错误:“找不到名称文档”.我看到在其他帖子中我们可以使用@ViewChild做类似的事情,但我不知道我们如何使用div,任何想法?
您可以通过添加 TemplateRef将@ViewChild与div一起使用.

模板

<div id ="myId" #myId>

零件

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对于熟悉Angular处理这类事情的方法非常好.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读