浅析Angular变更检测中的DOM更新机制_第1页
浅析Angular变更检测中的DOM更新机制_第2页
浅析Angular变更检测中的DOM更新机制_第3页
浅析Angular变更检测中的DOM更新机制_第4页
浅析Angular变更检测中的DOM更新机制_第5页
已阅读5页,还剩1页未读, 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

第浅析Angular变更检测中的DOM更新机制变更检测是Angular中很重要的一部分,也就是模型和视图之间保持同步。在日常开发过程中,我们无需了解变更检测,因为Angular都帮我们完成了这一部分工作,让开发人员更加专注于业务实现,提高开发效率和开发体验。但是如果想要深入使用框架,或者想要写出高性能的代码而不仅仅只是实现了功能,就必须要去了解变更检测,它可以帮助我们更好的理解框架,调试错误,提高性能等。

Angular的DOM更新机制

我们先来看一个小例子。

当我们点击按钮的时候,改变了name属性,同时DOM自动被更新成新的name值。

那现在有一个问题,如果我改变name的值后,紧接着把DOM中的innerText输出出来,它会是什么值呢?

import{Component,ViewChild,ElementRef}from@angular/core

@Component({

selector:my-app,

templateUrl:./ponent.html,

styleUrls:[./ponent.CSS]

exportclassAppComponent{

name=Empty

@ViewChild(textContAIner)textContainer:ElementRef;

normalClick():void{

=HelloAngular

console.log(this.textContainer.nativeElement.innerText);

}

你答对了吗?

那这两段代码中到底发生了什么呢?

如果我们用原生JS来编写这段代码,那么点击按钮后的视图肯定不会发生任何变化,而在Angular中却让视图发生了变化,那它为什么会自动把视图更新了呢?这离不开一个叫做zone.js的库,简单来说,它是对发生值改变的事件做了一些处理,这个会在后面的部分详细讲解,这里暂时知道这个就可以了。

如果我不想让这个库做这些处理,Angular还为我们提供了禁用zone.js的方法。

可以在main.ts中设置禁用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(duction){

enableProdMode();

platformBrowserDynamic().bootstrapModule(AppModule,{

ngZone:noop

.catch(err=console.error(err));

当我们禁用zone.js,视图并未发生更新。到源码里找一下视图更新的相关代码。

classApplicationRef{

/**@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=[];

*Getalistofcomponenttypesregisteredtothisapplication.

*Thislistispopulatedevenbeforethecomponentiscreated.

ponentTypes=[];

*Getalistofcomponentsregisteredtothisapplication.

ponents=[];

this._onMicrotaskEmptySubscription=this._zone.onMicrotaskEmpty.subscribe({

next:()={

this._zone.run(()={

this.tick();

*Invokethismethodtoexplicitlyprocesschangedetectionanditsside-effects.

*Indevelopmentmode,`tick()`alsoperformsasecondchangedetectioncycletoensurethatno

*furtherchangesaredetected.Ifadditionalchangesarepickedupduringthissecondcycle,

*bindingsintheapphaveside-effectsthatcannotberesolvedinasinglechangedetection

*pass.

*Inthiscase,Angularthrowsanerror,sinceanAngularapplicationcanonlyhaveonechange

*detectionpassduringwhichallchangedetectionmustcomplete.

tick(){

NG_DEV_MODEthis.warnIfDestroyed();

if(this._runningTick){

consterrorMessage=(typeofngDevMode===undefined||ngDevMode)

ApplicationRef.tickiscalledrecursively:

thrownewRuntimeError(101/*RuntimeErrorCode.RECURSIVE_APPLICATION_REF_TICK*/,errorMessage);

try{

this._runningTick=true;

for(letviewofthis._views){

view.detectChanges();

if(typeofngDevMode===undefined||ngDevMode){

for(letviewofthis._views){

view.checkNoChanges();

catch(e){

//Attention:DontrethrowasitcouldcancelsubscriptionstoObservables!

this._zone.runOutsideAngular(()=this._exceptionHandler.handleError(e));

finally{

this._runningTick=false;

}

大致解读一下,这个ApplicationRef是Angular整个应用的实例,在构造函数中,zone(zone库)的onMicrotaskEmpty(从名字上看是一个清空微任务的一个subject)订阅了一下。在订阅里,调用了tick(),那tick里做了什么呢?

思考:上次说了最好订阅不要放到constructor里去订阅,这里怎么这么不规范呢?

当然不是,上次我们说的是Angular组件里哪些应该放constructor,哪些应该放ngOnInit里的情况。但这里,ApplicationRef人家是一个service呀,只能将初始化的代码放constructor。

在tick函数里,如果发现这个tick函数正在执行,则会抛出异常,因为这个是整个应用的实例,不能递归调用。然后,遍历了所有个views,然后每个view都执行了detectChanges(),也就是执行了下变更检测,什么是变更检测,会在后面详细讲解。紧接着,如果是devMode,再次遍历所有的views,每个view执行了checkNoChanges(),检查一下有没有变化,有变化则会抛错(后面会详细说这个问题,暂时跳过)。

那好了,现在也知道怎么能让它更新了,就是要调用一下ApplicationRef的tick方法。

import{Component,ViewChild,ElementRef,ApplicationRef}from@angular/core

@Component({

selector:app-root,

templateUrl:./ponent.html,

styleUrls:[./ponent.scss]

exportclassAppComponent{

name=Empty

@ViewChild(textContainer)textContainer:ElementRef={}asany;

constructor(privateapp:ApplicationRef){}

normalClick(

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论