简体   繁体   中英

how can I include a javascipt code in angular 2+?

This is the HTML code:

<div id="myNav" class="overlay">
        <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
        <div class="overlay-content">
          <a href="#">About</a>`enter code here`
          <a href="#">Services</a>
          <a href="#">Clients</a>
          <a href="#">Contact</a>
        </div>
      </div>

      <h2>Fullscreen Overlay Nav Example</h2>
      <p>Click on the element below to open the fullscreen overlay navigation menu.</p>
      <p>In this example, the navigation menu will slide in, from left to right:</p>
      <span style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776; open</span>

where should I include this script tag in angular project for it to work?

<script>
    function openNav() {
      document.getElementById("myNav").style.width = "100%";
    }

    function closeNav() {
      document.getElementById("myNav").style.width = "0%";
    }
    </script>

Accessing the DOM directly isn't a good idea in Angular. You could, in theory, access DOM using methods like document.getElementById() or document.querySelector() in the component controller. But don't do it.

There are numerous other better ways to manipulate the DOM from the controller. One simple and quick way in your case would be to use [style.width.%] attribute property binding. Try the following

component.html

<div [style.width.%]="customWidth" id="myNav" class="overlay">

And in the controller you could do the following

component.ts

export class SampleComponent implements OnInit {
  customWidth = 100;   // <-- default width percentage

  public openNav() {
    this.customWidth = 100;
  }

  public closeNav() {
    this.customWidth = 0;
  }

  ngOnInit() {
  }
}

There are many more refined controls provided by Angular to modify the DOM. For eg, you could use many other CSS units like [style.width.px] , [style.width.em] , [style.width.in] and so on. You could apply multiple styles using ngStyle . For more advanced DOM features, look into Angular Renderer2 .

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