Angular2进阶之如何避免Dom误区
前言
Angular2的设计目标本来就是要让浏览器和DOM独立。DOM是复杂的,因此使组件与它分离,会让我们的应用程序,更容易测试和重构。为了支持跨平台,Angular还通过抽象封装了不同平台的差异。
内容
1.为什么不能直接操作DOM?
Angular2采用AOT静态编译模式,这种形式下需要我们的模板类型必须是稳定和安全的,直接使用javascript和jquery语言是不稳定,因为他们的编译不会提前发现错误,所以angular2才会选择javascript的超集typescript语言(这种语言编译期间就能发现错误)。
2.三种错误操作DOM的方式:
@Component({...})
exportclassHeroComponent{
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']
})
exportclassProductComponentimplementsOnInit,AfterViewInit{
@ViewChild('dia')dia:ElementRef;定义子试图
ngOnInit(){
/**1.
*创建一个文本
*/
this.dia.nativeElement.innerHTML="这只是一个测试的文档";
/**2.
*添加click事件
*/
letul=this.element.nativeElement.querySelector('ul');
this.render2.listen(ul,"click",()=>{
this.render2.setStyle(ul,"background","blue");
ngAfterViewInit(){
/**3.
*修改背景颜色
*/
letli=this.element.nativeElement.querySelector('ul');
this.render2.setStyle(li,"background","red");
}
}
总结
学习一种语言其实我们首先应该去遵循他的规范,接受他和之前语言的不同之处,然后再去深入理解和之前的方式不一样在哪里,为什么这么做,否则我们无法理解这种语言的妙处,希望对你有帮助!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。