Angular view container删除view实例的过程

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

单步调试进入this.viewContainer.createEmbeddedView(this.templateRef);

embeddedview创建成功之后,进入renderView:

单步调试,Chrome断点停下来的地方,就是createEmbeddedView具体创建的视图位置:

应用程序调用viewContainer的clear方法清除里面包含的视图实例:

clear的实现逻辑是,在一个循环里删除尾部的视图实例直至container为空:

从detachView的注释能发现,不仅view实例从view container中移除,并且对应的DOM元素也从HTML页面中删除了:

/**
 * Detaches a view from a container.
 *
 * This method removes the view from the container's array of active views. It also
 * removes the view's elements from the DOM.
 *
 * @param {?} lContainer The container from which to detach a view
 * @param {?} removeIndex The index of the view to detach
 * @return {?} Detached LView instance.
 */
function detachView(lContainer, removeIndex) {
    if (lContainer.length <= CONTAINER_HEADER_OFFSET)
        return;
    /** @type {?} */
    const indexInContainer = CONTAINER_HEADER_OFFSET + removeIndex;
    /** @type {?} */
    const viewToDetach = lContainer[indexInContainer];
    if (viewToDetach) {
        /** @type {?} */
        const declarationLContainer = viewToDetach[DECLARATION_LCONTAINER];
        if (declarationLContainer !== null && declarationLContainer !== lContainer) {
            detachMovedView(declarationLContainer, viewToDetach);
        }
        if (removeIndex > 0) {
            lContainer[indexInContainer - 1][NEXT] = (/** @type {?} */ (viewToDetach[NEXT]));
        }
        /** @type {?} */
        const removedLView = removeFromArray(lContainer, CONTAINER_HEADER_OFFSET + removeIndex);
        addRemoveViewFromContainer(viewToDetach[TVIEW], viewToDetach, false, null);
        // notify query that a view has been removed
        /** @type {?} */
        const lQueries = removedLView[QUERIES];
        if (lQueries !== null) {
            lQueries.detachView(removedLView[TVIEW]);
        }
        viewToDetach[PARENT] = null;
        viewToDetach[NEXT] = null;
        // Unsets the attached flag
        viewToDetach[FLAGS] &= ~128 /* Attached */;
    }
    return viewToDetach;
}

待删除视图在container里的索引,通过CONTAINER_HEADER_OFFSET加上方法输入的removeIndex计算而成。

待删除的视图实例: