Access DOM element outside of Angular root compone

2020-06-19 09:56发布

问题:

Consider this index.html:

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

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?

回答1:

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