访问TemplateRef会在Angular2中给出一个空注释节点
在Angular2中构建自定义排序组件,但访问模板变量时遇到问题。我需要能够访问访问TemplateRef会在Angular2中给出一个空注释节点,angular,typescript,Angular,Typescript,在Angular2中构建自定义排序组件,但访问模板变量时遇到问题。我需要能够访问ng模板,以便根据提供的模板“克隆/标记”元素来创建放置区域 我尝试过使用@ViewChild(“dropzone”),但它也会返回一个空的注释节点 这是组件 @Component({ selector: "my-sortable", template: ` <ng-content select="my-sortable-content"></ng-content&g
ng模板
,以便根据提供的模板“克隆/标记”元素来创建放置区域
我尝试过使用@ViewChild(“dropzone”)
,但它也会返回一个空的注释节点
这是组件
@Component({
selector: "my-sortable",
template: `
<ng-content select="my-sortable-content"></ng-content>
`
})
export class SortableComponent implements AfterViewInit {
@Input() //@ContentChild("dropzone")
dzTemplate: any;
onAfterViewInit() {
// Outputs an object but the
// nativeElement is an empty
// comment node
console.log(this.dzTemplate);
}
}
@组件({
选择器:“我的排序表”,
模板:`
`
})
导出类SortableComponent实现AfterViewInit{
@Input()/@ContentChild(“dropzone”)
模板:任何;
onAfterViewInit(){
//输出一个对象,但
//nativeElement是空的
//注释节点
console.log(这个.dzTemplate);
}
}
这是HTML
<my-sortable [dzTemplate]="dropzone">
<ng-template #dropzone>
<p>Hey, I'm a drop zone!!</p>
</ng-template>
<my-sortable-content>
<div *ngFor="...">
...
</div>
</my-sortable-content>
</my-sortable>
嘿,我是一个投球区
...
我需要做一些类似的事情,最终需要使用角度核心
import { Component, AfterViewInit, ViewChild, forwardRef } from '@angular/core';
/* ... in component somewhere */
@ViewChild(forwardRef(() => SomeComponent)) // You can use a DI token I believe
private paginationControls: SomeComponent;
不过,任何类型的游戏都可能很棘手,试一试吧D您可能也需要使用-但我不确定
如果需要根据模板的类型更改行为,那么最好使用一些静态类型并切换到动态字符串或其他类型。我以前构建过componentID->component类型的映射,并使用它来使用
ComponentFactoryResolver
实例化新组件-这有点麻烦,因为您需要列出所有情况,但是如果您需要在sorter组件中下拉到组件的详细信息,那么您必须这样做(如果forwardRef最终不工作)。找到了解决方案。结果是ElementRef
对象具有方法createEmbeddedView()
它将返回一个EmbeddedViewRef
。从那里,我可以访问rootNodes属性中的DOM元素。这些节点尚未附加到任何元素,因此它们非常适合克隆/戳记。角度编译后没有ng template
元素。您可以从此模板读取ViewContainer
e引用变量,然后将组件添加到这个容器ID。你是说?我不这么认为。