Open In App

ng-content in Angular

Last Updated : 19 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The ng-content is used when we want to insert the content dynamically inside the component that helps to increase component reusability. Using ng-content we can pass content inside the component selector and when angular parses that content that appears at the place of ng-content.

Syntax: 

<ng-content select=”.app”></ng-content>

Approach:

  • Create an angular app to be used.
  • Create a component “geek” using command “ng g c geek”.
  • Then we use this component inside the app component and provide the ng-content inside “geek” component.
  • Using ng-content we are passing two things in geek component first is person position and second is year of experience.

 

Example:

app.component.html




<app-geek>
    <strong class="app">Senior Developer</strong>
    <strong class="app1">Experience : 5 years</strong>
</app-geek>
<hr>
  
<app-geek>
    <strong class="app">Application Developer</strong>
    <strong class="app1">Experience : 2 years</strong>
</app-geek>


geek.component.html




<h3>
    <span>Hello, I am </span>
    <ng-content select=".app"></ng-content>
</h3>
  
<h4>
    <ng-content select=".app1"></ng-content>
</h4>


When we need to pass multiple things inside the component selector then we have to provide them unique selector either any id or class so using that unique selector we can access particular content inside the ng-content. So here “select” inside the ng-content is used to take content with matching class name app or app1.

Output: Run this using “ng serve” command and then go to the browser and open “localhost:4200”.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads