如何使用“角度方式"在Angular 2中获取/设置/删除元素属性? [英] How to get/set/remove element attribute in Angular 2 using "the angular way"?

查看:65
本文介绍了如何使用“角度方式"在Angular 2中获取/设置/删除元素属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读一些有关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函数,例如setElementAttributesetElementClass等.

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.

所以我的问题很简单,如何将上述功能用作getremove版本?它们是否生活在另一个类中?或者例如,您如何处理属性或类?

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.

自定义渲染器示例

  • Custom renderer for Angular2
  • https://github.com/ralfstx/angular2-renderer-example/blob/master/src/custom-renderer.ts

这篇关于如何使用“角度方式"在Angular 2中获取/设置/删除元素属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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