Required @Input() properties

profile
Tim Deschryver
timdeschryver.dev
Warning

👀 Heads-up! If you're using Angular v16.0.0-next.4 or later, you can ignore this post. The Angular Compiler now supports required @Input() properties, so we do not need to resort to workarounds mentioned in this post. To create a required @Input() property, simply use the new required property while defining a required property: @Input({ required: true }) woopARequiredInput: string;

This week I got asked how to make a component’s input property required. Without giving it much thought I started my answer ‘well, you can just …’, then I stopped asking myself the same question. So I opened a new StackBlitz project and started exploring the options before giving an answer.

Before we start let’s imagine we’re creating a component HelloComponent to greet a person. In order to greet the person properly, the person property is required.

Adding a null check link

The first thing that came to my mind was to throw an error when the person property would be null or undefined.

This doesn’t change much except that it would throw a useful error message.
Before: ERROR TypeError: Cannot read property ‘name’ of null
After: ERROR TypeError: The input ‘Person’ is required

Using the selector link

To make the requirement explicit we can use the selector in the @Component decorator to require that the attribute on our component has to exist.

Resulting in the following error when we start the application or at compile time when the application is build Ahead of Time (AoT), if the HelloComponent doesn’t have a person attribute.

Outcome link

By putting the two together, I can say that I’m happy with the result.
If you got a better way or see a problem with this approach please feel free to let me know, feedback is as always welcome.
The question I’m asking myself right now, is if this is something that should be done in the first place… again let us know your opinion on this 😃.

Below you can find the two put together as well as the StackBlitz project ready for you to play with.

NOTE: I’m using _ngOnInit_ but like Isaac Mann mentioned you could also use _ngOnChanges_.

Feel free to update this blog post on GitHub, thanks in advance!

Join My Newsletter (WIP)

Join my weekly newsletter to receive my latest blog posts and bits, directly in your inbox.

Support me

I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.

Buy Me a Coffee at ko-fi.com PayPal logo

Share this post on

Twitter LinkedIn