简体   繁体   中英

Access DOM element outside of Angular root component

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM