繁体   English   中英

Angular 2:如何通过组件属性传递模板?

[英]Angular 2: How to pass down a template through a component property?

如何通过 angular 2 中的组件属性传递模板?

我只做了第一步:

@Component({
    selector: 'tab',
    template: `<div>#!HERE GOES THE HEADER TEMPLATE!#
                <ng-content></ng-content>
              </div>`
})
export class Tab {
    @Input() title: string;
    @Input() headerTemplate:string;
    ...

可以这样使用:

<tab [title]="'Some Title'" [header-template]="'<p>{{title}}</p>'">Some Content</tab>

那应该呈现:

<div><p>Some Title</p>Some Content</div>

在这一点上,我被困住了。

虽然这个问题很老,但有更好的解决方案。 不需要将字符串作为模板传递——这是非常有限的。 您可以创建一个元素并获取其“TemplateRef”并将其发送到将 TemplateRef 作为输入的组件。 一个组件实际上可以接受任意数量的 TemplateRef 作为输入,并且您可以在任意数量的地方注入这些模板。

请注意,不推荐使用 'template' 元素,并且应在所有情况下使用 'ng-template' 元素。

因此,在父组件中 -

<ng-template #thisTemplate>You Can put anything here, including other components</ng-template>

 <tab [template]="thisTemplate"></tab>

然后在 OP 的 tabs 组件中

 import { Component, Input, TemplateRef, ViewChild, ViewContainerRef } from '@angular/core'

.... 在它的模板中......

 <div #viewcontainer></div>

在组件中:

 @ViewChild('viewcontainer',{read:ViewContainerRef}) viewcontainer : ViewContainerRef;

 @Input() template : TemplateRef<any>;


 ngAfterViewInit() { 
     this.viewcontainer.createEmbeddedView(this.template);
 }

经过一些研究,我检查了有人已经为这个问题提供了一个优雅的解决方案。 https://github.com/valor-software/ngx-bootstrap/blob/development/src/tabs ,选项卡组件可以接收到选项卡标题的模板。 做得好!

检查代码,解决方案依赖于两个指令,一个特定于选项卡的指令: TabHeading和一个通用指令: NgTransclude

如那里所示,可以通过模板创建组件:

<tab>
    <template tab-heading>Tab 2</template>
    Tab 2 content
</tab>

如果有人可以更好地解释该实现,请这样做。

一种类似于透辉石的方法,但使用容器元素在模板中进行投影,而不是以编程方式:

父组件.html

<app-child [template]=“templateRef”></app-child>
<ng-template #templateRef>
  <p>hello, from defined in parent</p>
</ng-template>

子组件.ts

<ng-container *ngTemplateOutlet=“templateRef”></ng-container>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM