deojeff
deojeff

Reputation: 377

Angular 2: Wrapping a component inside a parent component

I'm trying to put a component inside a parent component, like how it could be done in React.

React example:

Parent Component:

<div>
  Hello from parent
  {this.props.children}
</div>

Child component:

<ParentComponent>
  Hello from child
</ParentComponent>

Basically what I'm trying to do is to include child in between the parent tag.

Passing an @Input of elements comes to mind, but it sounded so wrong and ugly.

Upvotes: 3

Views: 3937

Answers (2)

mohsenmadi
mohsenmadi

Reputation: 2377

Given that your child component has a selector, say it's called app-child, then inside the parent component's HTML template you call it like this:

<div>
  Hello from parent
  <app-child></app-child>
</div>

Now, all you have inside your child component's HTML will be displayed as is. Also, should you need to pass input from the parent to the child, you could do something like this:

<div>
  Hello from parent
  <app-child [objInChild]="valFromParent"></app-child>
</div>

where valFromParent is a value that the parent can provide, and objInChild is the object you annotate with @Input in your child's class component (say in the file child.component.ts) to receive the passed in value.

Upvotes: 2

abbas-ak
abbas-ak

Reputation: 642

Parent Component:

<div>
  Hello from parent
  <ng-content select=".txt"></ng-content>
</div>

Child component:

<ParentComponent>
  <ng-container class="txt">
        Hello from child
    </ng-container>
</ParentComponent>

Output: Hello from parent Hello from child

Upvotes: 4

Related Questions