How to avoid render wrapper for ng-content when it is not passed in Angular

Stepan Mikhaylyuk
Nov 5 · 1 min read

Imagine that you have component that receives ng-content, wrapes it with container. Most popular task is to avoid rendering wrapper.

Solution 1

The simplest solution, which you can use is css:empty.
But this solution has many restrictions:
1) Only one wrapper supports
2) Wrapper’s DOM node just hidden, but rendered.

Solution 2

Let’s look to solution from angular components community using form-field code as example

The main idea of this solution is getting content children by @ContentChildren decorator and check exists it or not.

Look at @ContentChildren docs.
As you see, selector — The directive type or the name used for querying.
That means that we should to use directive to mark passed ng-content and to get access to it by @ContentChildren. And this is reason why angular components needs MatSuffix directive with empty body.

In the end of this solution, to make it working, you should add MatSuffix to your App where you use form-field.
But, MatSuffix looks like service directive, and theoretically, you can have many directives like it — you should to provide @NgModule for your consumer, like it implemented in angular form-field

See dart angular example.

Thank you!

Stepan Mikhaylyuk

Written by

Software developer https://github.com/stepancar

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade