Open In App

Projecting Content into Components with ng-content

Last Updated : 14 Aug, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

In Angular, there are many ways to pass the data in our app. But sometimes we have complex HTML/typescript codes that are needed to pass into the component from outside. So if we want simplified code and don’t want to set the Html/typescript codes inside the server-component.html, then we can write the piece of code between opening and the closing element of the server-component tag(i.e. between ‹app-server›‹∕app-server› tag) and should change the component variables accordingly.

Example:

serverElement : 
{type:'server', name:'some-name', content:'some-value'}

app-component.html




<div class="container-fluid">
<div class="row">
<div class="col-md-6 col-sm-1">
<app-server-element *ngFor=
         "let ele of serverElements" [element]="ele">
    <div class="card-text" 
        *ngIf="ele.type === 'server'" style="color: yellow;"
         Element name rendered is {{ele.name}} 
         Element content rendered is {{ele.content}}
    </div>
</app-server-element>
</div>
</div>
</div>


ng-content:
There is a special directive (‹ng-content›‹∕ng-content›) that is needed to be added in the server-component.html template, in the place where we want to render the content. It serves as a Hook you place in a component, to mark the place for the component where it should add any content it finds between the opening and closing tag.
server-component.html




<div class="card">
    <div class="card-body"
        <h5 class="card-header text-uppercase">
            <strong>{{element.type}}</strong>
        </h5>
            <ng-content></ng-content> 
    </div>
</div>


serverElement :

{type:'server', name:'some-name', content:'some-value'}

app-component.ts




import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
serverelements=[{type:'server'
                name:"TestServer",
                comp:'Just a Test!'}];
onAddedServer(data: {servername: string, 
                     servercomponent: string}){
  this.serverelements.push({
    type:'server',
    name:data.servername,
    comp:data.servercomponent
  })
}


Output:

Element name rendered is "some-name"
Element content rendered is "some-value"

Here, we added the HTML code via ng-content Hook, we add it between the opening and closing tags and therefore it will be projected into the server-component. It is a nice feature, which is special if we think about building reusable widgets. But if its more complex Html code then property binding is not really the best solution because angular will escape HTML text there, and then ng-content is the great tool to have.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads