Content Projection in Angular - Part 1
Salman Kazmi
Posted on November 4, 2019
One of the more advanced topics in the study of the Angular framework is content projection. To understand this very important and interesting topic, we need to have a good understanding of how components work in Angular.
In this brief article, I try to explain what Content Projection actually is and what are the different ways Angular provides you to leverage this powerful feature.
Basically, content projection is a way by which we can provide an external template to a component thereby giving us the functionality to provide a template to a particular component to render. The component providing content projection may or may not have its own template.
Let’s look at a very basic example:
I have a component named demo as follows:
@Component({
selector: 'hello',
template: `<h1>Hello {{name}}!</h1>`
})
export class HelloComponent {
name: string = 'John!'
}
As we can see we have a variable defined ‘name’ that we use to show the name on the component’s template. If we change the name to some other, it is reflected in the template. We can also make it as an @Input
to take the value of ‘name’ from the parent component where this component would be used. Eg. @Input()name: string = 'John!'
So, now the use case for content projection kicks in. What if I wanted the user to provide the heading tag along with the name of the user. He can provide an <h1>
or an <h2>
tag along with the name as it suits him. This is where Angular’s content projection kicks in.
Let’s take another example to understand better:
@Component({
selector: 'hello',
template: `<ng-content></ng-content>`
})
export class HelloComponent {}
Look closely, in this example, we have used a tag called ng-content
provided to us by Angular to render a dynamic template that would be passed by the parent where this component would be used.
So, if I have a parent component say, DemoComponent as follows:
@Component({
selector: 'demo',
template: `
<hello><h1>Hello John!</h1></hello>
<hello><h5>Hello Doe!</h5></hello>
`
})
export class DemoComponent {}
Here we can see that I have used the HelloComponent as a child twice passing different templates each time between the opening and closing tags. Actually we can pass a complete HTML template that would be rendered where <ng-content>
is presently placed in the child (hello) component.
This is a very basic example to demonstrate how a template can be passed to a component thereby making the component's template dynamic. At its very core, content projection in Angular is pretty powerful offering various techniques to handle passed template which we will discover in the upcoming posts.
Hope you found this article useful.
Posted on November 4, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.