Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access DOM element outside of Angular root component

Tags:

angular

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?

like image 671
Unknown developer Avatar asked Apr 17 '18 08:04

Unknown developer


1 Answers

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);
  }
}
like image 58
Tomasz Kula Avatar answered Nov 28 '22 14:11

Tomasz Kula