Angular2 - Class - AppViewManager/EmbeddedViewRef

这里描述讲了些关于view的概念,太好了!

  • View就是一堆元素的组成,一起创建一起消灭
  • 一个view可以有多个View Containers
  • 元素里的内嵌的view 可以通过ViewContainerRef 来操作

开始不清楚怎么看到这个ViewRef,后来跟踪到 AppViewManager

  • Service exposing low level API for creating, moving and destroying Views.
  • Most applications should use higher-level abstractions like DynamicComponentLoader and ViewContainerRef instead.

动态加载知道有文章说。http://dreambo8563.github.io/2016/01/11/Angular2-DynamicComponentLoader-%E7%94%A8%E6%B3%95/

怎么用ViewContainerRef这里有说明

To access a ViewContainerRef of an Element, you can either place a Directive injected with ViewContainerRef on the Element, or you obtain it via AppViewManager.

The Component and its View are created based on the HostViewFactoryRef which can be obtained by compiling the component with Compiler.
Use AppViewManager to destroy the created Component and it’s Host View.

  • 当元素里有指令注入的时候可以拿到ViewContainerRef
  • ViewContainerRef 也可以通过AppViewManager拿到
  • Component 和他的view 通过Compiler的HostViewFactoryRef 来得到

来例子:

export class ParentApp {

viewRef: ViewRef;
constructor(public appViewManager: AppViewManager, compiler: Compiler) {
compiler.compileInHost(ChildComponent).then(function(hostProtoViewRef: HostViewFactoryRef ){
var a = hostProtoViewRef;
this.viewRef = appViewManager.createRootHostView(hostProtoViewRef, 'some-component', null);
console.log(this.viewRef);
return true;
})
}

}

看看输出是啥:

>hostProtoViewRef

>HostViewFactoryRef_ {_hostViewFactory: HostViewFactory}
_hostViewFactory: HostViewFactory
selector: "child-component"
viewFactory: viewFactory_HostChildComponent0(parentRenderer,viewManager,containerEl,projectableNodes,rootSelector,dynamicallyCreatedProviders,rootInjector)
arguments: null
caller: null
length: 7
name: "viewFactory_HostChildComponent0"
prototype: viewFactory_HostChildComponent0
__proto__: ()
<function scope>
__proto__: HostViewFactory
internalHostViewFactory: HostViewFactory
__proto__: HostViewFactoryRef_

hostViewRef就是此组件的容器标签其实就是 <child-component></child-component>

appViewManager.createRootHostView(hostProtoViewRef, 'some-component', null)

ViewRef_ {_view: AppView}
_view: AppView
changeDetectorRef: ChangeDetectorRef_
destroyed: false
internalView: AppView
rootNodes: Array[1]
__proto__: ViewRef_

appViewManager.createRootHostView(hostProtoViewRef, 'some-component', null).rootNodes
<some-component><div>good</div></some-component>

ViewRef 里可以拿到创建的内容和其他的信息

  • appViewManager 可以创建HostView/EmbeddedView
  • ViewContainer 是装载 这两种view的容器
  • 当前appViewManager 可以destroy view