简体   繁体   中英

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

How to pass down a template through a component property in angular 2?

I've only made the first steps:

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

That could be used something like this:

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

That should render:

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

At this point I'm stuck.

Though this question is very old, there are much better solutions available. There is no need to pass a string as a template - that is very limiting. You can create an element and get its 'TemplateRef' and send that to a component which takes TemplateRef as input. A component can take any number of TemplateRefs as input actually, and you can inject those templates in any number of places.

Note that the 'template' element is deprecated, and the 'ng-template' element should be used in all cases.

So, in a parent component -

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

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

Then in the tabs component from the OP

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

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

 <div #viewcontainer></div>

Down in the component :

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

 @Input() template : TemplateRef<any>;


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

After some research, I've checked that someone already has an elegant solution for this question. At https://github.com/valor-software/ngx-bootstrap/blob/development/src/tabs the tab component can receive a template to tab heading. Great work!

Checking the code the solution relies on two directives, a tab specific one: TabHeading and a generic one: NgTransclude )

As presented there, the component can be created passing a template:

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

If someone can give a better explanation of that implementation, please do.

An method similar to diopside's but using a container element for projection in the template rather than programmatically:

parent.component.html

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

child.component.ts

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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