-
Notifications
You must be signed in to change notification settings - Fork 26.6k
Description
Which @angular/* package(s) are relevant/related to the feature request?
core
Description
When a component is created via the createComponent
method on ViewContainerRef
, there are two ways inputs can currently be set:
- Setting properties directly on the component instance. This seems to generally not be recommended due to the changes not respecting lifecycle hooks.
- Using the
setInput
method on theComponentRef
. This seems to be the recommended method, however it comes with its own set of issues:
a. Thename
can be anystring
, and thus is not guaranteed to be the name of an actual input.
b. Thevalue
type isunknown
, so even if you are always using the right names, there is no way to have any sort of type-checking on the value itself.
Additionally, for both options, because the inputs are being set one-by-one, there is no way to check for missing required
inputs.
As a result, setting inputs on components created with createComponent
is quite a bit riskier than using components in templates. It would be great if the API for creating component instances dynamically in TypeScript felt just as robust as instantiating a component inside of a template. Additionally, improvements here this could trickle down to provide a better interface for setting inputs in other use cases e.g. Dialog creation in Angular Components.
Proposed solution
Add an inputs
field to the options parameter of createComponent
which allows passing in initial values for each input on the component. Ideally, this should:
- Have full type info matching the inputs on the component itself.
- Respect the
required
flag, so if an required input is missing, an error is passed along.
Alternatives considered
- Alternative signature for
setInput
onComponentRef
which allows setting inputs in a type safe manner. This would be a more flexible option than the proposed solution, but has no ability to check if required inputs have been set.