Angular 页面元素的DOM级别的删除过程

时间:2022-07-26
本文章向大家介绍Angular 页面元素的DOM级别的删除过程,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

我的Angular视图里有如下一组p节点,通过自定义指令控制:

<p>
  The condition is currently
  <span [ngClass]="{ 'a': !condition, 'b': condition, 'unless': true, 'fuck_false': false, 'fuck_true': true  }">{{condition}}</span>.
  <button
    (click)="condition = !condition"
    [ngClass] = "{ 'a': condition, 'b': !condition }" >
    Toggle condition to {{condition ? 'false' : 'true'}}
  </button>
</p>
<p *appUnless="condition" class="unless a">
  (A) This paragraph is displayed because the condition is false.
</p>

<p *appUnless="!condition" class="unless b">
  (B) Although the condition is true,
  this paragraph is displayed because appUnless is set to false.
</p>

condition值切换的时候,对应的p节点区域会对应地显示和隐藏。p节点的隐藏,其实并不是通过css类实现,而是直接把DOM元素从HTML页面中删除来实现的。

具体实现是在Angular brower.js里实现的:

/**
 * @fileoverview added by tsickle
 * Generated from: packages/animations/browser/src/render/animation_engine_next.ts
 * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
 */
class AnimationEngine {
    /**
     * @param {?} bodyNode
     * @param {?} _driver
     * @param {?} normalizer
     */
    constructor(bodyNode, _driver, normalizer) {
        this.bodyNode = bodyNode;
        this._driver = _driver;
        this._triggerCache = {};
        // this method is designed to be overridden by the code that uses this engine
        this.onRemovalComplete = (/**
         * @param {?} element
         * @param {?} context
         * @return {?}
         */
        (element, context) => { });
        this._transitionEngine = new TransitionAnimationEngine(bodyNode, _driver, normalizer);
        this._timelineEngine = new TimelineAnimationEngine(bodyNode, _driver, normalizer);
        this._transitionEngine.onRemovalComplete = (/**
         * @param {?} element
         * @param {?} context
         * @return {?}
         */
        (element, context) => this.onRemovalComplete(element, context));
    }

在AnimationEngine里实施删除操作:

最后调用的还是浏览器的原生实现removeChild来删除DOM元素。