简体   繁体   English

javascript中Angular中“属性指令”的方法

[英]Approaches in javascript of “Attributes directives” in Angular

I am learning Angular5. 我正在学习Angular5。 And I am reading the official documentation about Attribute Directeve 我正在阅读有关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. 当然,您可以使用标准JavaScript进入DOM并手动附加事件侦听器。 There are at least three problems with that approach: 1. You have to write the listeners correctly. 这种方法至少存在三个问题:1.您必须正确编写侦听器。 2. The code must detach the listener when the directive is destroyed to avoid memory leaks. 2.销毁指令后,代码必须分离侦听器,以避免内存泄漏。 3. Talking to DOM API directly isn't a best practice. 3.直接与DOM API交谈不是最佳实践。

Can you give me an example of this in javascript in order to compare the two approaches? 为了比较这两种方法,您可以在javascript中给我一个例子吗?

Angular 角度的

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

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

Native js 原生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. 在本机js中,您必须获取要绑定事件的元素,然后附加单击侦听器。 You can see angular binds the click event to the element for you since you use the attribute directive. 由于使用attribute指令,因此可以看到angular将click事件绑定到元素。

  2. In native js, when the component is destroyed you would have to detach/remove the event listener manually to avoid any memory leaks. 在本机js中,当组件被销毁时,您将必须手动分离/删除事件侦听器,以避免任何内存泄漏。 Angular does this for you automatically. Angular会自动为您执行此操作。

  3. Talking to DOM API directly isn't best practice. This is because angular is set up to run in other environments. 这是因为将angular设置为在其他环境中运行。 For example using angular universal you can pre-render your code on the server. 例如,使用angular Universal可以在服务器上预渲染代码。 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. 因此,直接与DOM API对话会导致事情破裂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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