Skip to content

Type safe apis for setting inputs #51878

Open

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.

Activity

  1. JeanMeche commented on Sep 22, 2023

    @JeanMeche
    Member

    This is hardly achievable since the input can be aliased an this is not represented in the typings. This is the same thing for required inputs, it's not represented in the type that the decorator has required: true (remember decorators have no effect on typings).

  2. cusher commented on Sep 23, 2023

    @cusher
    Author

    Ah. Is the AOT compiler is only able to catch and report problems in templates, and not in the TS code? I was hoping that since these sorts of errors bubble up in templates, that it would also be feasible to bubble them up in TS. If that's not the case, then I see how that's a problem...

    That being said, the current method of setInput is also not very dependable at scale, IMO. It is very reliant on testing to avoid bugs that "should" be caught by type checking, and even if you you do have extensive tests it breaks down if you make a change without properly updating tests, or do update tests but fail to update every invocation outside of tests. (When recently updating a project code-base to move from string keys to properties w/ type inference in another aspect, there were a shocking number of bugs that had crept in over the years for this exact reason that we discovered all at once.) So I'm reluctant to ever use something like that without strong guardrails in place.

    If it's just not feasible to add something more rigid, then it is what it is, we'll probably just continue using the props of the component instance with workarounds for our own use cases. Thanks for the response.

  3. BojanKogoj commented on Sep 25, 2023

    @BojanKogoj

    I'm currently facing the same issue. setInput() offers almost no guarantees, other than runtime exception for incorrect property: https://stackblitz.com/edit/stackblitz-starters-6zmbjw?file=src%2Fmain.ts

    If nothing else, some way to make input required would be nice.

  4. added
    area: core
    on Sep 27, 2023
  5. modified the milestone: needsTriage on Sep 27, 2023
  6. SebastianPodgajny commented on Oct 13, 2023

    @SebastianPodgajny
  7. cusher commented on Oct 13, 2023

    @cusher
    Author

    @SebastianPodgajny Really cool, impressive to see a purely TS solution!

    It would be great if there was a way to get this to work with existing components using regular @Inputs without needing to declare a separate NgInputs field... but it's not clear to me how that could be accomplished (or if it's even feasible).

    Maybe there's a way to leverage TS decorators for that? It seems at least somewhat plausible to me that the @Component decorator could "generate" extra type information for each of the @Inputs, then a similar scheme to what you provided could be used from there on... but easier said than done.

  8. Harpush commented on Feb 29, 2024

    @Harpush

    Can it be a specific signal inputs feature? With the new input function both typings and required can be inferred I believe. This issue seems really important and the new changes complement it.

  9. Harpush commented on Mar 1, 2024

    @Harpush

    Proposal:

    I did some type gymnastics to try and type signal inputs correctly for this issue to be feasible. The two main ideas are type safety in setInput and an option to set inputs (especially required) at createComponent call site. For brevity (it is possible though) I omitted model and just handled input. The idea is looking just on signal based input/models and not on decorators.

    The end result should be:

    const cp = this.vcr.createComponent(Counter, {
      signalInputs: {
        a: 1,
        c: 3
      }
    });
    
    cp.setSignalInput('a', 2);
    cp.setSignalInput('c', 2);
    
    // Hopefully possible too
    cp.setSignalInputs({
      a: 2,
      c: 2,
    });

    The important parts are:

    1. setSignalInputs full type safety - meaning a is the property name or alias if exists
    2. signalInputs is required and will be either an empty object with optional properties if no required inputs or an object with required inputs as required props. Here too aliases will work correctly in a type safe way.

    Changes in Angular

    The interface InputSignalWithTransform is the base interface which will change to inherit from a "real" base interface:

    interface BaseInputSignal<
      ReadT,
      WriteT,
      RequiredT extends boolean,
      AliasT extends string
    > {
      [SIGNAL]: InputSignalNode<ReadT, WriteT>;
      [ɵINPUT_SIGNAL_BRAND_READ_TYPE]: ReadT;
      [ɵINPUT_SIGNAL_BRAND_WRITE_TYPE]: WriteT;
      [ɵINPUT_SIGNAL_REQUIRED]: RequiredT;
      [ɵINPUT_SIGNAL_ALIAS]: AliasT;
    }

    This allows InputFunction to be a fully type safe interface in terms of required and alias.
    The interface InputOptions will need to know the new alias type too:

    interface InputOptions<ReadT, WriteT, AliasT extends string> {
      alias?: AliasT;
      transform?: (v: WriteT) => ReadT;
    }

    The usage will be almost similar to now but will return a more specific type:

    // BaseInputSignal<number | undefined, number | undefined, false, never>
    input<number>();
    // BaseInputSignal<number, number, false, never>
    input(2);
    // BaseInputSignal<string, number, false, never>
    input('2', { transform: (n: number) => n.toString() });
    // BaseInputSignal<string, number, false, 'hello'>
    input('2', {
      transform: (n: number) => n.toString(),
      alias: 'hello',
    });
    // BaseInputSignal<number, number, false, 'hello'>
    input(2, { alias: 'hello' });
    // BaseInputSignal<number, number, true, never>
    input.required<number>();
    // BaseInputSignal<string, number, true, never>
    input.required({
      transform: (n: number) => n.toString(),
    });
    // BaseInputSignal<string, number, true, 'hello'>
    input.required({
      transform: (n: number) => n.toString(),
      alias: 'hello',
    });

    The only missing declaration is required input with alias. Currently it is declared as input.required<number>({alias: 'hello'}) but this is not possible with typed alias and will require: input.required<number, 'hello'>({alias: 'hello'}) which isn't a good idea.
    For this case I propose a new option just for this case called type which will use a simple function const type = <T>(): T => undefined as T; and will be used like this:

    // BaseInputSignal<number, number, true, 'hello'>
    input.required({ type: type<number>(), alias: 'hello' });

    The actual InputFunction will look like this:

    interface InputFunction {
      <ReadT>(): BaseInputSignal<
        ReadT | undefined,
        ReadT | undefined,
        false,
        never
      >;
      <ReadT, TAlias extends string = never>(
        initialValue: ReadT,
        opts?: InputOptionsWithoutTransform<ReadT, TAlias>
      ): BaseInputSignal<ReadT, ReadT, false, TAlias>;
      <ReadT, WriteT, TAlias extends string = never>(
        initialValue: ReadT,
        opts: InputOptionsWithTransform<ReadT, WriteT, TAlias>
      ): BaseInputSignal<ReadT, WriteT, false, TAlias>;
      required: {
        <ReadT, TAlias extends string = never>(
          opts?: InputOptionsWithoutTransform<ReadT, TAlias> & {
            type?: ReadT;
          }
        ): BaseInputSignal<ReadT, ReadT, true, TAlias>;
        <ReadT, WriteT, TAlias extends string = never>(
          opts: InputOptionsWithTransform<ReadT, WriteT, TAlias>
        ): BaseInputSignal<ReadT, WriteT, true, TAlias>;
      };
    }

    At this point all the parts are ready and we can type the new setSignalInput and signalInputs options.

    // Helpers for the BaseInputSignal
    type GeneralBaseInputSignal = BaseInputSignal<any, any, any, any>;
    type BaseInputSignalAlias<T> = T extends BaseInputSignal<any, any, any, infer T>
      ? T
      : never;
    type BaseInputSignalRequired<T> = T extends BaseInputSignal<
      any,
      any,
      infer T,
      any
    >
      ? T
      : never;
    type BaseInputSignalWrite<T> = T extends BaseInputSignal<any, infer T, any, any>
      ? T
      : never;
    
    // Properties info extraction (mainly alias and required related)
    type AllInputSignalPropNames<CompT> = {
      [P in keyof CompT]: CompT[P] extends GeneralBaseInputSignal ? P : never;
    }[keyof CompT];
    type AllInputSignalAliasToPropNameMap<CompT> = {
      [P in AllInputSignalPropNames<CompT> as BaseInputSignalAlias<
        CompT[P]
      > extends never
        ? P
        : BaseInputSignalAlias<CompT[P]>]: P;
    };
    type InputSignalAliasByRequired<CompT, RequiredT extends boolean> = {
      [AliasT in keyof AllInputSignalAliasToPropNameMap<CompT>]: BaseInputSignalRequired<
        CompT[AllInputSignalAliasToPropNameMap<CompT>[AliasT] & keyof CompT]
      > extends RequiredT
        ? AliasT
        : never;
    }[keyof AllInputSignalAliasToPropNameMap<CompT>];
    
    // Won't accept comp as will be implicit due to being in ComponentRef
    const setSignalInput = <
      CompT,
      AliasT extends keyof AllInputSignalAliasToPropNameMap<CompT>
    >(
      comp: Type<CompT>,
      key: AliasT,
      value: BaseInputSignalWrite<
        CompT[AllInputSignalAliasToPropNameMap<CompT>[AliasT] & keyof CompT]
      >
    ) => undefined;
    
    // Will be the type of the new property inside createComponent
    type SignalInputs<CompT> = {
      [P in InputSignalAliasByRequired<CompT, true>]: BaseInputSignalWrite<
        CompT[AllInputSignalAliasToPropNameMap<CompT>[P] & keyof CompT]
      >;
    } & {
      [P in InputSignalAliasByRequired<CompT, false>]?: BaseInputSignalWrite<
        CompT[AllInputSignalAliasToPropNameMap<CompT>[P] & keyof CompT]
      >;
    };

    With this we have fully type safe dynamic components with signal inputs 😀
    @dylhunn I hope this can help the idea being implemented

  10. MaximSagan commented on Jun 14, 2024

    @MaximSagan

    @JeanMeche @pkozlowski-opensource Any thought on the above proposal or something similar? Input metadata integrated into the typing seems the way to go here.

  11. MaximSagan commented on Jun 14, 2024

    @MaximSagan

    I'm currently facing the same issue. setInput() offers almost no guarantees, other than runtime exception for incorrect property

    It's not even a runtime exception. Just a console error, so we can't even capture it. Would be nice if setInput() at least returned a boolean indicating whether the operation was successful or not.

  12. felixgeissler commented on Aug 13, 2024

    @felixgeissler

    I ran into this using a material/cdk overlay as well.
    Just dropping a Stackblitz here in case someone need a quick reproduction:
    https://stackblitz.com/edit/stackblitz-starters-snb2ag?file=src%2Fmain.ts

  13. 4 remaining items

  14. JeanMeche commented on Sep 12, 2024

    @JeanMeche
    Member

    test could be considered private in your case and it is an implementation detail and not an exposed api.

  15. pkozlowski-opensource commented on Sep 12, 2024

    @pkozlowski-opensource
    Member

    Since this is (IMHO) problem only with signal-based input

    @4zriel this is not the case. Assigning directly to the input property has number of problems, regardless of the signal-based inputs:

    • it doesn't take aliases into account (already discussed);
    • does not mark OnPush components as dirty (contrary to a changing input in a template);
    • doesn't trigger lifecycle hooks, skipping important ones like ngOnChanges

    Long story short: direct assignment to the input property goes through very different code paths as compared to bindings in a template and is not something we recommend doing.

  16. 4zriel commented on Sep 12, 2024

    @4zriel

    @pkozlowski-opensource thx for this tl;dr ;)
    So maybe it should be described as not recomended? Or even whole documentation should be change since for now it states that setInput correctly marks components for change detection and triggers lifecycle hooks:

        /**
         * Updates a specified input name to a new value. Using this method will properly mark for check
         * component using the `OnPush` change detection strategy. It will also assure that the
         * `OnChanges` lifecycle hook runs when a dynamically created component is change-detected.
         *
         * @param name The name of an input.
         * @param value The new value of an input.
         */
    
  17. alixroyere commented on Sep 12, 2024

    @alixroyere

    Since this is (IMHO) problem only with signal-based input (for 'old' ones, we could simply use componentRef.nameOfInput = 'newValue' )

    nameOfInput doesn't exist on componentRef, but on componentInstance. This means that this is not working for old required input neither because they need to be set before the instance is created.

    So maybe it should be described as not recomended?

    Direct assignment is not recommended, not using setInput. That's the opposite

  18. daniel-sc commented on Feb 5, 2025

    @daniel-sc

    I think extending ComponentRef<C> with the following delcaration would solve many (not all) problems:

    setInputTyped<K extends keyof C & string>(
      name: K, 
      value: value: C[K] extends InputSignal<any> ? ReturnType<C[K]> : C[K]
    ): void;

    Of course there are the obvious limitations:

    1. key is not restricted to inputs but any (public) member
    2. alias is not considered
    3. signal inputs with transform are not correctly typed (this could be resolved by a little better typing, though)

    IMHO, this still would be a huge improvement for most use cases!

    In case there is positive feedback, I'm happy to make a PR (covering the case of signal inputs with transform as well).

  19. w-biggs commented on Jun 11, 2025

    @w-biggs

    Now that signal inputs are becoming more and more the standard, there not being a type-safe way to manually set inputs (e.g. in unit tests) is definitely frustrating. Direct assignment definitely had downsides (needing to call detectChanges() every time, mainly) but it was at least type-safe. If aliases are what make this particularly difficult, I think falling back to "any" for properties that aren't recognized (e.g. aliases) would still be preferable to nothing.

  20. Hetty82 commented on Sep 2, 2025

    @Hetty82

    Same issue with the createComponent inputBinding parameters.

  21. changed the title [-]Type safe Input setting on components created with createComponent[/-] [+]Type safe apis for setting inputs[/+] on Sep 2, 2025
  22. added
    canonical
    on Sep 2, 2025
  23. JeanMeche commented on Sep 2, 2025

    @JeanMeche
    Member

    I'll mark this as a canonical issue : A redesign of the input apis is necessary to address type safety for:

    • componentRef.setInput
    • inputBindings
    • createComponpoent / viewContainerRef.createComponent

    The current limitation is that input aliases are not reflected in the typing while being necessary to cover the scope of all those apis.

  24. janne-hyoetylae-med commented on Apr 27, 2026

    @janne-hyoetylae-med

    @daniel-sc

    I think extending ComponentRef<C> with the following delcaration would solve many (not all) problems:

    If anybody wants to have their own helper in the mean time that uses @daniel-sc's solution, with the addition that non-signal properties are disallowed, you can do this:

    function setInputTyped<C, K extends keyof C & string>(
        component: ComponentFixture<C> | ComponentRef<C>,
        name: K,
        value: C[K] extends InputSignal<any> ? ReturnType<C[K]> : never,
    ): void {
      if (component instanceof ComponentFixture) {
        component.componentRef.setInput(name, value);
      } else {
        component.setInput(name, value);
      }
    }
    

    (Note: the never makes sure that only signal inputs are allowed to be set)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: corecanonicalcore: dynamic view creationcore: inputs / outputs

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions