应用程序调用viewContainer的clear方法清除里面包含的视图实例:
![50f11047471cdbf378fbcd59c0cc3ff8.png](https://i-blog.csdnimg.cn/blog_migrate/ad92ae1e2fe9af2ba38fcbbc24c7ce4f.jpeg)
clear的实现逻辑是,在一个循环里删除尾部的视图实例直至container为空:
![6f6a960f4205f084353324d8ae738bb4.png](https://i-blog.csdnimg.cn/blog_migrate/28fe7eec174080a12002e1a7248147ba.jpeg)
从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计算而成。
![638289666735ee0c7507a07f8a3afae5.png](https://i-blog.csdnimg.cn/blog_migrate/af8cd44f57683703f9c2d8548844b50e.jpeg)
待删除的视图实例:
![b8efd01c4de0e744efd5d4f539ff5166.png](https://i-blog.csdnimg.cn/blog_migrate/dad11c09673eb78f01a578793b5e6abe.jpeg)