我的子组件看起来像:
...
@Component({
selector: '[child-component]'
templateUrl: './child.template.html'
})
...
和我的父模板,例如:
<span child-component [someInput]="123"></span>
现在我想渲染我的子组件的内容,周围没有<span>
容器。我想要父组件模板中根本没有容器,只想要子组件模板的内容。
我已经尝试了其他一些标签。
<ng-content>
(完全不渲染(<ng-template>
(嵌入式模板上的组件:(<ng-container>
(无法在"节点"上执行"appendChild"(
提前感谢!
终于找到了一个工作的解决方案!
我的子组件如下所示:
@Component({
selector: 'child-component'
templateUrl: './child.template.html'
})
export class ChildComponent {
@ViewChild('childComponentTemplate') childComponentTemplate: TemplateRef<any>;
}
我的子模板如下所示:
<ng-template #childComponentTemplate>
... some content ...
</ng-template>
和我的父模板,例如:
<child-component #wrapper [someInput]="123"></child-component>
<ng-container *ngTemplateOutlet='wrapper.childComponentTemplate'></ng-container>
这样就根本没有包装器了。
您的用例只能使用 CSS 来解决,只需将child-component
设置为display: contents
,
child-component {
display: contents;
}
如display: contents
文档中所述,这会导致组件看起来好像是元素父级的直接子级。
此方法可以避免 ExpressionChangedAfterItHasBeenCheckedError 错误。
子组件:
@Component({
selector: 'child-component'
templateUrl: './child.template.html'
})
export class ChildComponent implements OnInit {
@ViewChild('childTemplate', {static: true}) childTemplate: TemplateRef<any>;
constructor(
private view: ViewContainerRef
) {}
ngOnInit(): void {
this.view.createEmbeddedView(this.currentUserTemplate);
}
}
父组件:
<child-component></child-component>