Angular ngIf指令的工作原理

425 阅读1分钟

/**

  • Represents a container where one or more views can be attached to a component.

  • Can contain host views (created by instantiating a

  • component with the createComponent() method), and embedded views

  • (created by instantiating a TemplateRef with the createEmbeddedView() method).

  • A view container instance can contain other view containers,

  • creating a view hierarchy.

  • @see ComponentRef

  • @see EmbeddedViewRef

  • @publicApi

  • @abstract
    */
    class ViewContainerRef {


    }

ViewContainerRef可以包含Host view和embedded view.

给原型链上设置函数,都是空的实现:

执行template函数:

检测到一个节点具有ngIf的Directive,因此执行createDirectivesInstances:

调用NgIf_Factory工厂函数:

NgIf构造函数里两个参数,应用开发人员可以直接使用:

loadComponent会触发change detection:

第二次进入到executeTemplate方法:

这个值来自应用开发人员给ngIf指定的类型为boolean的condition值。

如果condition为true,则显示内容到this._thenTemplateRef里:

在此处绘制视图:

先创建,再渲染:

开始创建原生的h2节点了:

这里触发将动态创建的h2节点,插入到DOM tree中的操作:

在这里插入图片描述

最后的comment节点,值从container变成了如下的注释:

而一开头发现的comment节点,是什么时候创建的?

这个container的值什么时候被替换的?

在此处的comment属性值被修改:

更多Jerry的原创文章,尽在:“汪子熙”: