jjzjj

javascript - Angular 2 : How to pass down a template through a component property?

coder 2025-03-06 原文

如何在 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 作为输入,并且您可以在任意数量的地方注入(inject)这些模板。

请注意,'template' 元素已弃用,在所有情况下都应使用 'ng-template' 元素。

因此,在父组件中 -

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

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

然后在 OP 的选项卡组件中

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

.... somehwere in its template ....

 <div #viewcontainer></div>

在组件中:

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

 @Input() template : TemplateRef<any>;


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

关于javascript - Angular 2 : How to pass down a template through a component property?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33299758/

有关javascript - Angular 2 : How to pass down a template through a component property?的更多相关文章

随机推荐