首页 > 解决方案 > Angular2+ 渲染一个完全没有任何包装标签的组件

问题描述

我的子组件看起来像:

...
@Component({
    selector: '[child-component]'
    templateUrl: './child.template.html'
})
...

和我的父模板,如:

<span child-component [someInput]="123"></span>

现在我想在没有<span>容器的情况下渲染我的子组件的内容。我的父组件模板中根本不需要容器,只需要子组件模板的内容。

我已经尝试了其他一些标签。

提前致谢!

标签: angulardomangular2-templateangular2-directivesangular2-ngcontent

解决方案


终于找到了一个可行的解决方案!

我的子组件看起来像:

@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>

这种方式根本没有包装器。


推荐阅读