您好,欢迎访问一九零五行业门户网

Angular2使用Dom有哪些注意事项

这次给大家带来angular2使用dom有哪些注意事项,angular2使用dom的注意事项有哪些,下面就是实战案例,一起来看一下。
前言
angular2的设计目标本来就是要让浏览器和dom独立。dom是复杂的,因此使组件与它分离,会让我们的应用程序,更容易测试和重构。为了支持跨平台,angular还通过抽象封装了不同平台的差异。
内容
1.为什么不能直接操作dom?
angular2采用aot静态编译模式,这种形式下需要我们的模板类型必须是稳定和安全的,直接使用javascript和jquery语言是不稳定,因为他们的编译不会提前发现错误,所以angular2才会选择javascript的超集typescript语言(这种语言编译期间就能发现错误)。
2.三种错误操作dom的方式:
@component({ ... })export class herocomponent { constructor(private _elementref: elementref) {} dobadthings() {  $('id').click(); //jquery  this._elementref.nativeelement.xyz = ''; //原生的elementref  document.getelementbyid('id'); //javascript }}
3.angular2如何dom操作的机制?
为了能够支持跨平台,angular 通过抽象层封装了不同平台的差异。比如定义了抽象类 renderer、renderer2 、抽象类 rootrenderer 等。此外还定义了以下引用类型:elementref、templateref、viewref 、componentref 和 viewcontainerref 等。
4.正确操作dom的方式(elementref和renderer2):
product.component.html
<p>商品信息</p><ul> <li *ngfor="let product of datasource| async as list">  {{product.title}} </li></ul><p #dia></p>
product.component.ts
import { component, oninit,renderer2, viewchild,elementref,afterviewinit} from '@angular/core';@component({ selector: 'app-product', templateurl: './product.component.html', styleurls: ['./product.component.css']})export class productcomponent implements oninit,afterviewinit { @viewchild('dia') dia:elementref ;定义子试图 ngoninit() { /**1. *创建一个文本 */  this.dia.nativeelement.innerhtml=这只是一个测试的文档; /**2.  *添加click事件  */ let ul=this.element.nativeelement.queryselector('ul');  this.render2.listen(ul,click,()=>{   this.render2.setstyle(ul,background,blue);ngafterviewinit(){/**3. *修改背景颜色 */ let li=this.element.nativeelement.queryselector('ul'); this.render2.setstyle(li,background,red); }}
总结
学习一种语言其实我们首先应该去遵循他的规范,接受他和之前语言的不同之处,然后再去深入理解和之前的方式不一样在哪里,为什么这么做,否则我们无法理解这种语言的妙处,希望对你有帮助!
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
从零开始操作angularjs实现应用模块化
怎样使用vue做出单页应用前端路由
以上就是angular2使用dom有哪些注意事项的详细内容。
其它类似信息

推荐信息