A New Way to Set Inputs on Angular ComponentRefs
When creating dynamic components in our applications or writing tests, we use the component reference instance
property to change input values. For example:
This approach does, however, come with four drawbacks:
- Setting input properties manually wouldn’t trigger the
NgOnChanges
lifecycle hook - It’s challenging to test
OnPush
components since they are not marked for check - As a result of input
aliasing
, setting input properties was fragile because a property name on a component may differ from the actual input name - It doesn’t throw an error if the input doesn’t exist
Since v14.1.0, Angular added the setInput()
method to the component reference, making the above issues a thing of the past:
These modifications unify inputs
across dynamically created components and the ones referenced in templates.
There is only one drawback to this approach over using the instance directly — it isn’t typed. You can type-safe it like this if you don’t use an alias:
The following article explains how to create a stricter typed version of the above:
Follow me on Medium or Twitter to read more about Angular and JS!