Developer Snippet Diary

ng-content in Angular | insert html from parent to child component| Angular 15+

ng-content is a built-in Angular directive that allows you to create a content projection, which is a way of passing HTML content from a parent component to a child component. It works as a placeholder within the child component's template, where the parent component's content will be inserted.

Using ng-content enables you to create reusable and customizable components, as it allows the child component to define a structure while letting the parent component determine the content.

ie.

Products.component.html //parent

<div>
	<app-single-product>
		<h5 class="card-title">Card title 1</h5>
	</app-single-product>
	<app-single-product>
		<h5 class="card-title">Card title 2</h5>
	</app-single-product>
</div>

single-product.component.html //child

<div class="card" style="width: 18rem;">
  <div class="card-body">
    <ng-content></ng-content>
    <p class="card-text">Best card.</p>
    <a href="#" class="btn btn-primary">Go somewhere</a>
  </div>
</div>

ng content  render all html that is given inside  <app-single-product> </app-single-product>

Posted by: R GONDAL
Email: rizikmw@gmail.com