简体   繁体   中英

Approaches in javascript of “Attributes directives” in Angular

I am learning Angular5. And I am reading the official documentation about Attribute Directeve

In particular, I read that in the section Respond to user-initiated events :

Of course you could reach into the DOM with standard JavaScript and attach event listeners manually. There are at least three problems with that approach: 1. You have to write the listeners correctly. 2. The code must detach the listener when the directive is destroyed to avoid memory leaks. 3. Talking to DOM API directly isn't a best practice.

Can you give me an example of this in javascript in order to compare the two approaches?

Angular

// html
<button (click)="onClick()">Click Me</button>

// ts
onClick(){
    // run some code on click
}

Native js

<button id="my-button">Click Me</button>

// js
// attach click event
document.getElementById('my-button').addEventListener('click', onClick);
// remove click event on component destroy
document.getElementById('my-button').removeEventListener('click', onClick);

As the docs are saying

  1. In native js, you have to grab the element you want to bind the event to then attach the click listener. You can see angular binds the click event to the element for you since you use the attribute directive.

  2. In native js, when the component is destroyed you would have to detach/remove the event listener manually to avoid any memory leaks. Angular does this for you automatically.

  3. Talking to DOM API directly isn't best practice. This is because angular is set up to run in other environments. For example using angular universal you can pre-render your code on the server. In this case the server does not have a window object. So talking to the DOM API directly would cause things to break in universal.

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