Angular : Content Projection

Joshua Markasky
3 min readJan 19, 2021

So last post I talked about how to create re-usable components. Making re-usable components is great but there will be times where you want to add some static text or images to a component without sacrificing the re-useableness of it. Let me show a example of what I mean.

Here we have a basic form with a component used three times for each input field. This is the same form we used in the last post, talking about re-usable components. So lets say we want to add labels to our form inside our component but how do we had label to the component so each input field has its own unique label. Well that’s where content projection comes in. Remember I’m just using this example to show you how it works, there will be more practical use’s for this. So first lets create a content tag in our input component.

So we added our ngcontent tag and we add the attribute “select” which we made it equal to the “Label”. One thing to note is generally when your using a class attribute will have to but a . in front the “select” of the child component or if your using a ID attribute it will be a # but we are using the word “Label” all that matters is that it matches to in the parent component. So lets now edit our parent form component to project our labels onto our input components.

For each use of our input component we add a label inside of the tag and add the class “Label” to each one. Now this is what we see in our form in the browser.

We get a label on each input in our form. We are projecting a label on the form based on what we put inside the input tag with the class “Label”. If we dont put on then there simple wont be any labels shown but everything else will work as same. This makes the component more flexible and can be custom to a certain situation increasing its usability

Connect with me on linkedIn: www.linkedin.com/in/joshua-markasky47

follow me on Twitter: https://twitter.com/MarkaskyJ

Checkout my YouTube channel: https://www.youtube.com/channel/UCgRkJcniRghYpSpzKQlEYvQ

--

--