这次给大家带来Angular怎样避免使用Dom的误区,Angular使用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
商品信息
- {{product.title}}
登录后复制
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"); }}
登录后复制
相信看了本文案例你已经掌握了方法,更多精彩请关注【创想鸟】其它相关文章!
推荐阅读:
vue内置指令使用总结
怎样使用FileReader API创建Vue的文件阅读器
react怎样实现页面代码分割和按需加载
以上就是Angular怎样避免使用Dom的误区的详细内容,更多请关注【创想鸟】其它相关文章!