如何使用“角度方式"在Angular 2中获取/设置/删除元素属性? [英] How to get/set/remove element attribute in Angular 2 using "the angular way"?
问题描述
我一直在阅读一些有关Angular 2陷阱和避免的文章,其中之一是围绕不直接访问DOM.
I've been reading some articles about Angular 2 pitfalls and what to avoid, one of those things revolves around not accessing the DOM directly.
我注意到Renderer
非常有用,因为它包含一些可以帮助避免DOM陷阱的方法.但是,我注意到它不包含任何get
函数,仅包含set
函数,例如setElementAttribute
,setElementClass
等.
I noticed that the Renderer
is quite useful since it contains some methods that can help avoid the DOM pitfall. However, I noticed that it doesn't contain any get
functions, only set
functions such as setElementAttribute
, setElementClass
and so on.
所以我的问题很简单,如何将上述功能用作get
和remove
版本?它们是否生活在另一个类中?或者例如,您如何处理属性或类?
So my question is rather simple, how do you use the above functions but as the get
and remove
version? Do they live in another class or how do you work with retrieving attributes or classes for example?
推荐答案
Angular2不提供任何从DOM中获取任何内容的支持,除了ElementRef
和事件.
Angular2的方法是维护模型中的状态并更新DOM以反映该状态.
Angular2 doesn't provide any support to get anything from the DOM except ElementRef
and events.
The Angular2 way is to maintain the state in the model and update the DOM to reflect that state.
如果您需要读取DOM,则可以使用直接DOM访问或提供自定义Renderer
,该自定义Renderer
提供默认Renderer
中缺少的功能.
If you need to read from the DOM you can use direct DOM access or provide a custom Renderer
that provides the features you're missing in the default Renderer
.
自定义渲染器示例
- 用于Angular2的自定义渲染器
- https://github.com/ralfstx/angular2-renderer-example/blob/master/src/custom-renderer.ts
- Custom renderer for Angular2
- https://github.com/ralfstx/angular2-renderer-example/blob/master/src/custom-renderer.ts
这篇关于如何使用“角度方式"在Angular 2中获取/设置/删除元素属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!