Simplifying Content Projection in Angular

In Angular, content projection is used to project content in a component. Let’s take a closer look at how it works:

Content projection allows you to insert a shadow DOM in your component. To put it simply, if you want to insert HTML elements or other components in a component, then you do that using concept of content projection. In Angular, you achieve content projection using < ng-content >< /ng-content >.  You can make reusable components and scalable application by right use of content projection.

To understand content projection, let us consider GreetComponent as shown in the code listing below:

image

Now if you use GreetComponent in another component, and want to pass a greeting message from the parent component, then you should use the @Input() decorator. This way, a modified GreetComponnet will look like the listing below:

image

Using the @Input() decorator, you can pass a simple string to the GreetComponnet, but what if you need to pass different types of data to the GreetComponent such as:

  1. Inner HTML
  2. HTML Elements
  3. Styled HTML
  4. Another Component etc.

To pass or project styled HTML or another component, content projection is used. Let us modify the GreetComponent to use content projection in this code:

We are using to project content in the GreetComponent. When you use the GreetComponent, you’ll pass content as shown below:

Read full article on the Infragistics blog

Published by

Dhananjay Kumar

Dhananjay Kumar is Developer Evangelist for Infragistics. He is a 8 times Microsoft MVP and well respected Developer Advocate in India.He is the author of 900+ Blog Posts, and can often be found speaking around India at conferences and hosting free workshops for programmers across the country. So far, he has hosted 60 free workshops on various topics like JavaScript, Angular, WCF, ASP.NET MVC, C#, Azure etc. Follow him on twitter @debug_mode for all the updates about his blog posts and workshops. You can send him email at debugmode [at] outlook [dot] com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s