2

A parent component passes 2 templates and data to a child component. In the child component only the template without data is shown. How to show the template with data passed to it?

Parent component file:

export class ParentComponent {
  parentdata: string = 'String from parent with data';
  constructor() { }
}

Parent html/template file:

<app-child2
  [templateHeader]="list"
  [templateContent]="detail"
  [datafromparent]="parentdata">
</app-child2>

<ng-template #detail>
  Some data passed to it from outside
</ng-template>

<ng-template #list let-data="datafromparent">
  {{data}}
</ng-template>

The child component is: yup, will remove the ts-ignore ;-)

export class Child2Component {
  // @ts-ignore
  @Input() templateHeader: TemplateRef<any> | null;
  // @ts-ignore
  @Input() templateContent: TemplateRef<any> | null;
  @Input() datafromparent: string | undefined;
  constructor() { }
}

The child html/template file is:

<div class="header-css-class">
  <ng-container
    *ngTemplateOutlet="templateHeader; context: { data: datafromparent }">
  </ng-container>
</div>
<div class="content-css-class">
  <ng-container
    *ngTemplateOutlet="templateContent">
  </ng-container>
</div>

I hope you can help me with this one, because it is quite instructive for solving many (generic) problems.

2
  • 1
    Could you please post the full component code or add a stackblitz url? Commented May 31, 2022 at 8:12
  • It is already solved. See below. Thank you for willing to help! Commented May 31, 2022 at 9:56

1 Answer 1

2
+50

Use the name of the data item from the context passed to the template (for clarity I changed the name from data to datafromcontext):

// in the child template
<ng-container
   *ngTemplateOutlet="templateHeader; context: { datafromcontext: datafromparent }">
</ng-container>

// in the parent template
<ng-template #list let-data="datafromcontext">
  {{data}}
</ng-template>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.