前言
Angular2的設(shè)計(jì)目標(biāo)本來就是要讓瀏覽器和DOM獨(dú)立。DOM是復(fù)雜的,因此使組件與它分離,會(huì)讓我們的應(yīng)用程序,更容易測(cè)試和重構(gòu)。為了支持跨平臺(tái),Angular還通過抽象封裝了不同平臺(tái)的差異。
內(nèi)容
1.為什么不能直接操作DOM?
Angular2采用AOT靜態(tài)編譯模式,這種形式下需要我們的模板類型必須是穩(wěn)定和安全的,直接使用javascript和jquery語言是不穩(wěn)定,因?yàn)樗麄兊木幾g不會(huì)提前發(fā)現(xiàn)錯(cuò)誤,所以angular2才會(huì)選擇javascript的超集typescript語言(這種語言編譯期間就能發(fā)現(xiàn)錯(cuò)誤)。
2.三種錯(cuò)誤操作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操作的機(jī)制?
為了能夠支持跨平臺(tái),Angular 通過抽象層封裝了不同平臺(tái)的差異。比如定義了抽象類 Renderer、Renderer2 、抽象類 RootRenderer 等。此外還定義了以下引用類型:ElementRef、TemplateRef、ViewRef 、ComponentRef 和 ViewContainerRef 等。
4.正確操作DOM的方式(ElementRef和Renderer2):
product.component.html
<div>商品信息</div><ul> <li *ngFor="let product of dataSource| async as list"> {{product.title}} </li></ul><div #dia></div>
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. *創(chuàng)建一個(gè)文本 */ this.dia.nativeElement.innerHTML="這只是一個(gè)測(cè)試的文檔"; /**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"); }}
總結(jié)
學(xué)習(xí)一種語言其實(shí)我們首先應(yīng)該去遵循他的規(guī)范,接受他和之前語言的不同之處,然后再去深入理解和之前的方式不一樣在哪里,為什么這么做,否則我們無法理解這種語言的妙處,希望對(duì)你有幫助!
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注