[Angular] ng-content for beginners


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


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


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

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

Simply a software developer

Love podcasts or audiobooks? Learn on the go with our new app.

React Native — A Deep Dive — Part 1.

JavaScripts Prototype Inheritance Explained For Dummies

Migrate from AngularJS to React

Not All Those Who Render are Lost

Brain Brash Recap With The JS — Part 001

Different ways of chaining http calls in Angular using observables

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Eden Park

Eden Park

Simply a software developer

More from Medium

ViewportScroller service in angular

Browser with console mode on. Logs the scroll position

Angular Component Interaction

Preloading Strategy in Angular12

Everything you need to know about angular reactive forms minus validations