访问Angular根组件之外的DOM元素

时间:2018-04-17 08:30:31

标签: angular

考虑一下这个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?我可以使用vanilla Javascript,但有一种Angular方式吗?

1 个答案:

答案 0 :(得分:1)

你能得到的最好的就是这样的。不幸的是,我们仍然需要使用全局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);
  }
}