Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass content to child including renderable parts in Angular?

I have two components: parent and child, with the following markup. It’s vital to this example that the child fetches its own data to render and it must not be provided by the parent. As it’s design now, it works as supposed to.

The parent.

<h1>I'm the papa</h1>
<app-lookup>
  <div>Some fixed content</div>
  <div>Some dynamic content (soon)</div>
</app-lookup>

The child.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<h1>I'm the sonny</h1>
<div *ngFor="let item of items">
  <span>{{item.name}}</span>
  <span>{{item.value}}</span>
</div>
<div>Total: {{items.count}}</div>
<ng-content></ng-content>

At this stage, I realized that I don’t know how to render something that’s internal in the child as a part of the content passed from the parrent. In the example above, the total is presented (when it’s retried from a HTTP request subscribed to). But I’d like to control how it’s presented by passing a template for it to the child.

Wish-for, pseudo-code (not working, naturally, since items doesn’t exist in the parent) would be this.

<h1>I'm the papa</h1>
<app-lookup>
  <div>Some fixed content</div>
  <div>The cool total: {{items.count}}</div>
</app-lookup>

I can’t use @Input/@Output because I want to encapsulate the data in the child. I’ve found a bunch of blogs on the child content and on data exchange. But I failed to find one that illustrates how to pass a template to be rendered with the child’s fields. Naturally, the parent needs to guess the fields’ names. I’m fine with that (and in case those aren’t present, I’d just display nothing.

>Solution :

You can use a template reference variable (I called "data" to makes a look more comfortable)

<app-lookup #data>
  <div>Some fixed content</div>
  <!--see that you use data.any-property-of child -->
  <div>The cool total: {{data.items.count}}</div>
</app-lookup>

NOTE, really I don’t like so much because you force know the properties of the child

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading