Skip to content

Type safe apis for setting inputs #51878

@cusher

Description

@cusher

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:

  1. Setting properties directly on the component instance. This seems to generally not be recommended due to the changes not respecting lifecycle hooks.
  2. Using the setInput method on the ComponentRef. This seems to be the recommended method, however it comes with its own set of issues:
    a. The name can be any string, and thus is not guaranteed to be the name of an actual input.
    b. The value type is unknown, 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:

  1. Have full type info matching the inputs on the component itself.
  2. Respect the required flag, so if an required input is missing, an error is passed along.

Alternatives considered

  • Alternative signature for setInput on ComponentRef 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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions