在Angular根组件之外访问DOM元素 [英] Access DOM element outside of Angular root component

查看:90
本文介绍了在Angular根组件之外访问DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下index.html:

Consider this index.html:

<div id="test-case">
  Hello
  <button type="button">Press me</button>
</div>
<app> </app>

其中 app root component.是否可以从应用程序组件内部访问test-case元素 并通过Angular方法操作button click event?我可以使用香草Javascript,但是有没有Angular的方法?

where app is the root component. Is it possible to access test-case element from inside the app component and manipulate button click event via Angular methods? I could use vanilla Javascript, but is there an Angular way of doing that?

推荐答案

您能得到的最好的就是这样.不幸的是,我们仍然必须使用全局document.querySelector.

The best you can get is something like this. Unfortunatelly we still have to use the global document.querySelector.

index.html

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>App</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>

<body>
  <div id="hello">Hello</div>
  <pwpl-root></pwpl-root>
</body>

</html>

app.component.ts

import { Component, Renderer2 } from '@angular/core';

@Component({
  selector: 'app',
  template: ``,
})
export class AppComponent {
  constructor(private renderer: Renderer2) {
    const hello = document.querySelector('#hello');
    this.renderer.listen(hello, 'click', console.log);
  }
}

这篇关于在Angular根组件之外访问DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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