[Angular] ng-content for beginners

Eden Park
2 min readApr 30, 2022

#Introduction

As a Angular developer, you might have seen <ng-content></ng-content> and wondered what it is actually doing and what would be use cases for that. Before diving into the code and examples, let’s ponder on the definitions related to ng-content

What is ng-content?

The <ng-content> element specifies where to project content inside a component template.[1]

What is content-projection then?

Content projection is a pattern in which you insert, or project, the content you want to use inside another component. For example, you could have a Card component that accepts content provided by another component.[2]

My definition of ng-content

Use ng-content when you want to inject html elements into a child component

Still I don’t get it

#Example

Some people might better understand after they have seen the example code than just reading definitions. The list below is the use case where I might use ng-content for.

#Inject html elements from a parent to a child component

You have an article.component and article-content.component. An article component has a responsibility to render a title and article-content component is for showing contents only. How would you do it?

article.component.html (parent) would look like this. I will inject html elements to a child component.

article-content.component.html (child) would look like this. I will get html elements using <ng-content></ng-content>from a parent component.

As the example above, showing the title of the article is not a responsibility of article-content.component; it is more of a article.component’s job. You now can inject any html elements into a child component using ng-content.

You can see the full code on StackBlitz

#References

[1] https://angular.io/guide/content-projection

[2] https://angular.io/guide/content-projection

--

--