2

I have a component called wrapper and this is to be reused with different child components. I referred this SO question and this article. But they seem to address only if I know which child component I would be rendering before hand. But in my case, I might even just pass a div or h2 in there.

Here's the minimal reproduction code

<app-wrapper>
  <app-edit-address></app-edit-address>
</app-wrapper>

<app-wrapper>
  <div>
    <label>Edit Email</label>
    <input />
  </div>
</app-wrapper>

<app-wrapper>
  <h2>
    Unauthorized 
  </h2>
</app-wrapper>

In React I can easily render them just by writing {props.children} but Angular I don't know how. How can I render children dynamically without knowing the children before hand?

Pushkin
  • 3,336
  • 1
  • 17
  • 30

1 Answers1

3

What you are trying to do is called Content Projection in Angular. You can simply use ng-content to project anything.

@Component({
  selector: 'app-wrapper',
  template: `
    <div class="wrapper">
       <ng-content></ng-content>
    </div>
  `
})
export class WrapperComponent {}

And you can use it any way you like

<app-wrapper>
  <app-edit-address></app-edit-address>
</app-wrapper>

<app-wrapper>
  <div>
    <label>Edit Email</label>
    <input />
  </div>
</app-wrapper>

<app-wrapper>
  <h2>
    Unauthorized 
  </h2>
</app-wrapper>

Whatever you pass between opening and closing tags will be projected into where ng-content is.

Bunyamin Coskuner
  • 8,719
  • 1
  • 28
  • 48