Angular - 5.13-Project content into components with ng-content

So we learn a lot throughout this section. We learned how to circulate data, how to access elements of our DOM and how to use local references. Now our application is much more dynamic. We have many more tools to interact between the different parts we have in our application.

Now there’s another way to get data flowing. The last way right now in our server element component here. Right now we’re checking to see if we have a server type or a model server type, right? But sometimes you have complex HTML like this that you want to pass into a component from the outside. So imagine that you don’t want to put that inside the component here. I rather cut it into the application component. You want to add this here between opening and closing your own component. And here we should just have to replace "element" with "server element". And we should expect that to work, right?

So if we save this and let it reload and we add a new server, we don’t get an error. But the content is also not there and this is the default behavior. Everything you place between opening and closing your own component is lost by default. It is simply removed from the MOD. Angular won’t take care of it, but you can change that. There is a special directive and it is a directive even if it looks like a component but it does not have its own model.

A special guideline that you can add to the template of these serveElement components. Here, where I want to render the content, I can add NG content in opening and closing. Again, this is always a directive simply using this item selector, and it serves as a hook that you can place in your component to mark where Angular should add any content it finds between opening and closing the tag here.

So, with this content in this case with this small addition, you should see that once you’ve saved it and let it reload, if we add this and click add a server, you will now see that the content is back. It looks exactly like it was before, but technically something totally different works or happens here. Now we add this via the NG content crochet. We add it between the opening and closing tags and so it will be projected in your component, so in your serverElement component. An interesting feature, especially if you’re thinking about building reusable widgets like a tab widget where each tab will likely have content that comes from another source and you don’t want to go through a property link, which would always be an alternative.

But if it’s a more complex HTML code, new sentence: Property binding is not the best solution because Angular will escape HTML texts to avoid cross-site script attacks. And you could get around that somehow. But NG content is how you want to display it, and it’s a great tool at your disposal.