为什么不直接在Angular中与DOM交互? [英] Why not to interact with the DOM directly in Angular?

查看:71
本文介绍了为什么不直接在Angular中与DOM交互?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到,为了安全和性能而直接与DOM交互是不明智的.避免使用下面的语法来选择元素.

I have read that it is not wise to interact with the DOM directly both for security and performance. Avoiding using syntax like below to select Elements.

const itemToManipulate = document.getElementById('example');

因此,我读到的一个不错的解决方法是使用ElementRef指令. 但是,由于紧密耦合,继续找到Angular Documents的建议,什么是紧密耦合?

So I read a good work around is to use ElementRef Directive. But go on to find the Angular Documents advise against this because of tight coupling, what is tight coupling?

在此处的文档中找到

我决定使用ViewChild,就像这样...

I settled for using a ViewChild, like so...

@ViewChild('itemToManipulate') public item: ElementRef<any>; 

这是否会导致我应关注的任何不良行为(在安全/性能方面),是否存在与DOM交互的最佳实践,还是不应该在Angular(6/7)中完成?

Does this lead to any unwanted behaviour I should be concerned about (security / performance wise) and is there a best practice for interacting with the DOM, or should this not be done within Angular (6 / 7)?

预先感谢.

推荐答案

Angular使用生命周期挂钩确定如何以及何时渲染和更新组件:

Angular uses Lifecycle Hooks that determine how and when components will be rendered and updated:

组件的生命周期由Angular管理.

A component has a lifecycle managed by Angular.

Angular会创建,渲染,创建和渲染其子级,在其数据绑定属性更改时对其进行检查,并在将其从DOM中删除之前将其销毁.

Angular creates it, renders it, creates and renders its children, checks it when its data-bound properties change, and destroys it before removing it from the DOM.

直接DOM访问或操作会破坏这些生命周期挂钩,从而导致整个应用程序出现意外行为.

Direct DOM access or manipulation can corrupt these lifecycle hooks, leading to unexpected behavior of your whole app.

紧耦合 表示组件(不是角组件(但程序或系统的任何部分)彼此高度依赖.在Angular上下文中,改变组件的状态(例如变量)直接影响其渲染.因此,如果直接使用ElementRef访问DOM元素,则无法在Web worker中运行组件代码(例如,使用多线程).

Tight coupling means that components (not Angular components but any parts of a program or system) highly depend on each other. In the Angular context, changing a component's state (e. g. variables) directly influences its rendering. Thus, if you access a DOM element directly with ElementRef, you cannot run your component code in a web worker (to use multi-threading for example).

这篇关于为什么不直接在Angular中与DOM交互?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆