When creating components, particularly core components, our goal is to make them as modular and as flexible and grant the consumers a high level of control over what they can pass.

For example, let’s say we build a generic error component. What we want is to give our consumers the flexibly to create it by using one of three options:

They can choose to use the default text value

They can choose to use their own text which can be static or dynamic

They can choose to pass their own template

Let’s create the error component in question, and see how we can meet the above requirements:

We have an error input that accepts either a string or a reference to a template . We also define a default error message in case the consumer doesn’t pass anything.

Additionally, we have the isTemplate getter, which performs a simple check to let us know whether we need to render a custom template; It’s as simple as that.

Now we can use the component whichever way we need:

So far so good, but our inner code still isn’t reusable, and we need to repeat it for any component that requires this kind of functionality. A better approach would be to create a custom structural directive, that ensures our code is DRY and reusable.

We want to be able to write something like the following:

Much cleaner. Let’s look at the directive’s implementation:

The directive is pretty straightforward; If the type of the input value is TemplateRef we render it; otherwise, we render the default template, which in our example is: <p>{{error}}</p> which can display the default error message or a custom one.

If you’re not familiar with Angular structural directives, I recommend the following resources: