Pass html defined in parent to child

Viewed 8052

I am trying to define some html in my parent component that can be passed to the child component. Is this possible? I have tried a couple of things like this: How to pass an expression to a component as an input in Angular2?, but I did not have any luck. Maybe my syntax was wrong. I was a little confused with the let. Appreciate all the help and any explanations to help me understand this better.

@Component({
    selector: 'app-my-parent',
    template: `
    <div>other parent html</div>
    <app-my-child [property]="value">
        <ng-template #someTemplate">value.first</ng-template>
    </app-my-child>
    <app-my-child [property]="value">
        <ng-template #someTemplate">value.second</ng-template>
    </app-my-child>
    `
})
export class MyParent {
}
@Component({
    selector: 'app-my-child',
    template: `
    <div>other child html</div>
    how do I access the template from here? Is there a way to do binding with templates? 

})
export class MyChild {
      @Input() property;
}
2 Answers

You need to add an ng-content tag to your child component so angular knows it's supposed to transclude content and where to put the content:

@Component({
    selector: 'app-my-child',
    template: `
    <div>other child html</div>
    <ng-content></ng-content>
    `
})
export class MyChild {
}

then you need to remove the ng-template tags, because that tells angular to actually not render these things at all, because they're templates meant to be used elsewhere

Using it in the parent is super simple:

<app-my-child>Anything put between these component tags will be transcluded to the ng-content tag</app-my-child>

As @bryan60 pointed out, the child template needs an <ng-content>. In the parent, everything you put within the child selector will be displayed at the ng-content location immediately before the AfterContentInit() lifecycle hook executes:

Parent component template:

<child-cmp>
  <p>This will appear within ng-content of ChildComponent</p>
</child-cmp>

Child component template:

  <h2>I am ChildComponent</h2>
  <ng-content></ng-content>

Live demo

Related