站長資訊網(wǎng)
        最全最豐富的資訊網(wǎng)站

        淺析Angular變更檢測中的DOM更新機制

        淺析Angular變更檢測中的DOM更新機制

        前端(vue)入門到精通課程,老師在線輔導(dǎo):聯(lián)系老師
        Apipost = Postman + Swagger + Mock + Jmeter 超好用的API調(diào)試工具:點擊使用

        變更檢測是Angular中很重要的一部分,也就是模型和視圖之間保持同步。在日常開發(fā)過程中,我們無需了解變更檢測,因為Angular都幫我們完成了這一部分工作,讓開發(fā)人員更加專注于業(yè)務(wù)實現(xiàn),提高開發(fā)效率和開發(fā)體驗。但是如果想要深入使用框架,或者想要寫出高性能的代碼而不僅僅只是實現(xiàn)了功能,就必須要去了解變更檢測,它可以幫助我們更好的理解框架,調(diào)試錯誤,提高性能等。【相關(guān)教程推薦:《angular教程》】

        Angular的DOM更新機制

        我們先來看一個小例子。

        淺析Angular變更檢測中的DOM更新機制

        當(dāng)我們點擊按鈕的時候,改變了name屬性,同時DOM自動被更新成新的name值。

        那現(xiàn)在有一個問題,如果我改變name的值后,緊接著把DOM中的innerText輸出出來,它會是什么值呢?

        import { Component, ViewChild, ElementRef } from '@angular/core';  @Component({   selector: 'my-app',   templateUrl: './app.component.html',   styleUrls: [ './app.component.css' ] }) export class AppComponent  {   name = 'Empty';    @ViewChild('textContainer') textContainer: ElementRef;    normalClick(): void {     this.name = 'Hello Angular';      console.log(this.textContainer.nativeElement.innerText);   } }
        登錄后復(fù)制

        你答對了嗎?

        那這兩段代碼中到底發(fā)生了什么呢?

        如果我們用原生JS來編寫這段代碼,那么點擊按鈕后的視圖肯定不會發(fā)生任何變化,而在Angular中卻讓視圖發(fā)生了變化,那它為什么會自動把視圖更新了呢?這離不開一個叫做zone.js的庫,簡單來說,它是對發(fā)生值改變的事件做了一些處理,這個會在后面的部分詳細(xì)講解,這里暫時知道這個就可以了。

        如果我不想讓這個庫做這些處理,Angular還為我們提供了禁用zone.js的方法。

        可以在main.ts中設(shè)置禁用zone.js。

        import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';  import { AppModule } from './app/app.module'; import { environment } from './environments/environment';  if (environment.production) {   enableProdMode(); }  platformBrowserDynamic().bootstrapModule(AppModule, {   ngZone: 'noop' })   .catch(err => console.error(err));
        登錄后復(fù)制

        淺析Angular變更檢測中的DOM更新機制

        當(dāng)我們禁用zone.js,視圖并未發(fā)生更新。到源碼里找一下視圖更新的相關(guān)代碼。

         */ class ApplicationRef {     /** @internal */     constructor(_zone, _injector, _exceptionHandler, _initStatus) {         this._zone = _zone;         this._injector = _injector;         this._exceptionHandler = _exceptionHandler;         this._initStatus = _initStatus;         /** @internal */         this._bootstrapListeners = [];         this._views = [];         this._runningTick = false;         this._stable = true;         this._destroyed = false;         this._destroyListeners = [];         /**          * Get a list of component types registered to this application.          * This list is populated even before the component is created.          */         this.componentTypes = [];         /**          * Get a list of components registered to this application.          */         this.components = [];         this._onMicrotaskEmptySubscription = this._zone.onMicrotaskEmpty.subscribe({             next: () => {                 this._zone.run(() => {                     this.tick();                 });             }         });         ...     }  /**      * Invoke this method to explicitly process change detection and its side-effects.      *      * In development mode, `tick()` also performs a second change detection cycle to ensure that no      * further changes are detected. If additional changes are picked up during this second cycle,      * bindings in the app have side-effects that cannot be resolved in a single change detection      * pass.      * In this case, Angular throws an error, since an Angular application can only have one change      * detection pass during which all change detection must complete.      */     tick() {         NG_DEV_MODE && this.warnIfDestroyed();         if (this._runningTick) {             const errorMessage = (typeof ngDevMode === 'undefined' || ngDevMode) ?                 'ApplicationRef.tick is called recursively' :                 '';             throw new RuntimeError(101 /* RuntimeErrorCode.RECURSIVE_APPLICATION_REF_TICK */, errorMessage);         }         try {             this._runningTick = true;             for (let view of this._views) {                 view.detectChanges();             }             if (typeof ngDevMode === 'undefined' || ngDevMode) {                 for (let view of this._views) {                     view.checkNoChanges();                 }             }         }         catch (e) {             // Attention: Don't rethrow as it could cancel subscriptions to Observables!             this._zone.runOutsideAngular(() => this._exceptionHandler.handleError(e));         }         finally {             this._runningTick = false;         }     }  }
        登錄后復(fù)制

        大致解讀一下,這個ApplicationRef是Angular整個應(yīng)用的實例,在構(gòu)造函數(shù)中,zone(zone庫)的onMicrotaskEmpty(從名字上看是一個清空微任務(wù)的一個subject)訂閱了一下。在訂閱里,調(diào)用了tick(),那tick里做了什么呢

        思考: 上次說了最好訂閱不要放到constructor里去訂閱,這里怎么這么不規(guī)范呢?

        當(dāng)然不是,上次我們說的是Angular組件里哪些應(yīng)該放constructor,哪些應(yīng)該放ngOnInit里的情況。但這里,ApplicationRef人家是一個service呀,只能將初始化的代碼放constructor

        在tick函數(shù)里,如果發(fā)現(xiàn)這個tick函數(shù)正在執(zhí)行,則會拋出異常,因為這個是整個應(yīng)用的實例,不能遞歸調(diào)用。然后,遍歷了所有個views,然后每個view都執(zhí)行了detectChanges(),也就是執(zhí)行了下變更檢測,什么是變更檢測,會在后面詳細(xì)講解。緊接著,如果是devMode,再次遍歷所有的views,每個view執(zhí)行了checkNoChanges(),檢查一下有沒有變化,有變化則會拋錯(后面會詳細(xì)說這個問題,暫時跳過)。

        那好了,現(xiàn)在也知道怎么能讓它更新了,就是要調(diào)用一下ApplicationReftick方法。

        import { Component, ViewChild, ElementRef, ApplicationRef } from '@angular/core'; @Component({   selector: 'app-root',   templateUrl: './app.component.html',   styleUrls: ['./app.component.scss'] }) export class AppComponent  {   name = 'Empty';    @ViewChild('textContainer') textContainer: ElementRef = {} as any;    constructor(private app: ApplicationRef){}    normalClick(): void {     this.name = 'Hello Angular';      console.log(this.textContainer.nativeElement.innerText);      this.app.tick();   } }
        登錄后復(fù)制

        果然,可以正常的更新視圖了。

        我們來簡單梳理一下,DOM的更新依賴于tick() 的觸發(fā),zone.js幫助開發(fā)者無需手動觸發(fā)這個操作。好了,現(xiàn)在可以把zone.js啟用了。

        那什么是變更檢測呢?繼續(xù)期待下一篇哦。

        贊(0)
        分享到: 更多 (0)
        網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號
        主站蜘蛛池模板: 久久精品国产欧美日韩| 精品水蜜桃久久久久久久| 日韩欧美亚洲国产精品字幕久久久| 国产成人精品cao在线| 亚洲精品自产拍在线观看动漫| 日韩欧国产精品一区综合无码| 国产精品手机在线观看你懂的| 无码人妻精品一区二区三区66| 国产精品视频免费观看| 久久久国产精品亚洲一区| 国产高清在线精品一区| 国产精品 日韩欧美| 亚洲欧美国产精品第1页| 精品国产精品国产偷麻豆| 欧美精品国产一区二区| 四虎永久在线精品免费一区二区| 国产精品伦理久久久久久| 久久国产美女免费观看精品| 无码人妻丰满熟妇精品区| 久久综合九色综合精品| 亚洲国产精品自产在线播放| 福利姬在线精品观看| 久久国产成人亚洲精品影院| 精品国产a∨无码一区二区三区| 92国产精品午夜福利免费| 中文字幕精品一区二区精品| 日本精品一区二区三区在线观看| 亚洲欧美精品丝袜一区二区| 欧美精品免费线视频观看视频| 亚洲午夜精品一级在线播放放 | 91精品国产高清久久久久久91| 亚洲国产精品不卡毛片a在线| 精品综合久久久久久97超人| 在线中文字幕精品第5页| 国产成人精品日本亚洲专区| 国产精品视频一区二区三区四 | 亚洲国产精品第一区二区三区| 国产在线不卡午夜精品2021| 中文字幕日韩精品在线| 国产中文在线亚洲精品官网| 国产亚洲精品xxx|