在阅读
ViewContainerRef和
ComponentFactory的文档时,例如我们有方法
ViewContainerRef#createComponent有3个参数:componentFactory,injector和projectableNodes.
我已经尝试查找projectableNodes的含义以及它们如何在博客,教程和源代码中使用,但找不到多少.
在查找diff for for ngComponentOutlet directive时,我可以收集到的是,projectableNodes中的字符串被“投影”或呈现在创建的组件视图上(如ng-content可能).如果是这样,那就像我们ViewContainerRef#createEmbeddedView那样令人困惑.
我想知道这些投影节点是什么,并举例说明它们的用法.
可投影节点是节点元素(即实现
node interface的元素),它们被“投影”或换句话说,被转换到我们在组件模板中的ng-content.
原文链接:https://www.f2er.com/angularjs/143767.html例如,我们可以通过以下方式创建节点元素:
var myNode = document.createElement('div'); var text = document.createTextNode('this is my text'); myNode.appendChild(text);
然后我们可以使用上面的节点,方法如下:
constructor(private vcr:ViewContainerRef ) { } ngAfterViewInit() { let cmpFactory = this.vcr.resolveComponentFactory(MyDynamicComponent); let injector = this.vcr.parentInjector; var myNode = document.createElement('div'); var text = document.createTextNode('this is my text'); myNode.appendChild(text); this.vcr.createComponent(cmpFactory,injector,[ [ myNode ] ]) }
投影节点接受二维数组,因为我们可以进行多时隙转换,即多于一个ng内容.
以下是如何将可投影节点与ViewContainerRef#createComponent一起使用的完整示例.此示例动态创建一个包含transclsion / ng-content的组件:
import { Component,ViewContainerRef,ComponentFactoryResolver } from '@angular/core'; import { ComponentFactory,ComponentRef,Renderer } from '@angular/core'; @Component({ selector: 'sample',template: '<ng-content></ng-content><ng-content></ng-content>' }) export class Sample { } @Component({ selector: 'demo',template: '<p>Demo</p>',entryComponents: [Sample] }) export class DemoComponent { constructor(private vcr: ViewContainerRef,private cfr: ComponentFactoryResolver,private r: Renderer) { } ngAfterViewInit() { let cmpFactory = this.cfr.resolveComponentFactory(Sample); let injector = this.vcr.parentInjector; let demoCompEl = this.vcr.element.nativeElement; let projectedElA = this.r.createElement(demoCompEl,'p'); this.r.createText(projectedElA,'projectable content A'); this.r.detachView([projectedElA]); let projectedElB = this.r.createElement(demoCompEl,'p'); this.r.createText(projectedElB,'projectable content B'); this.r.detachView([projectedElB]); let projectedC = document.createElement('div'); let text = document.createTextNode('projectable content C'); projectedC.appendChild(text); let cmpRef = this.vcr.createComponent(cmpFactory,[[projectedElA],[projectedElB,projectedC]]); } }
输出:
Demo projectable content A projectable content B projectable content C
另外需要注意的是,在我们为可投影节点传递的2d数组中,每个1d数组条目具有属于一起的特定视图的根元素/将在单个ng内容块中一起渲染