Search code examples
htmlangularangular-directiveangular-components

How to pass content in between Angular child component selectors


I am trying to pass Data inside an Angular component selectors like its being done in Angular material or MD Bootstrap.Below is an example of simple Angular Material Card which displays the content in between the selectors enclosed in a Card.

<mat-card>Simple card</mat-card>

The output will be like this image

I am trying to replicate the same by declaring a child component with a container and the content should be placed in between the child component selector.

child.component.html

<div class=container></div>

child.component.ts

@Component({
selector: 'app-container',
templateUrl: './container.component.html',
styleUrls: ['./container.component.css']
 })

parent.component.html

<app-container> I am inside the container </app-container>

This is not working like the Material card and none of the text is displayed when it is enclosed by the component selectors.


Solution

  • You should use angular content projection using ng-content. use it as follows:

    <div class=container>
      <ng-content></ng-content>
    </div>
    

    If you want to pass multiple contents, you can use select attribute in ng-content to select a particular element using the tag name, class name or id name.

    app.component.html

    <app-container> 
      <header>Welcome</header>
      <p class="message">Hi, how are you</p>
      <footer>Copyright</footer>
    </app-container>
    

    parent.component.html

    <div class=container>
      <header>
       <ng-content select="header"></ng-content>
      </header>
      <section>
        <ng-content select="p.message"></ng-content>
      <section>
      <footer>
         <ng-content select="footer"></ng-content>
      </footer>
    </div>