Skip to content

Allow injecting ComponentRef of a component through DI  #47398

Open

Description

@Harpush

Which @angular/* package(s) are relevant/related to the feature request?

core

Description

As of angular 14 we have the new super useful setInput on ComponentRef for dynamic components. It finally allows fully CD aware dynamic inputs changing.
Currently if I want to extend a component with a directive and set inputs from it I need to do one of the two options:

  1. Change the inputs statically in the constructor
  2. Change inputs to get/set as ngOnChanges won't fire

Proposed solution

Allowing to inject ComponentRef of the host component instead of the actual instance. This way we could just use setInput to update inputs and have a full CD aware binding support not through the template.

Alternatives considered

  1. Change the inputs statically in the constructor only - Can't apply to directive input based changes or observable based changes
  2. Change inputs to get/set - Possible but annoying and "leaks" the knowledge of this component is being used from a directive outside. How can one explain why ngOnChanges was not used...
  3. Maybe not through ComponentRef but as any other way to use setInput from DI injected components

Activity

  1. added
    feature
    area: core
    on Sep 12, 2022
  2. modified the milestone: Backlog on Sep 12, 2022
  3. AndrewKushnir commented on Sep 12, 2022

    @AndrewKushnir
    Contributor

    (linking #8277 here as an additional use-case)

  4. angular-robot commented on Sep 13, 2022

    @angular-robot
    Contributor

    This feature request is now candidate for our backlog! In the next phase, the community has 60 days to upvote. If the request receives more than 20 upvotes, we'll move it to our consideration list.

    You can find more details about the feature request process in our documentation.

  5. angular-robot commented on Oct 23, 2022

    @angular-robot
    Contributor

    Just a heads up that we kicked off a community voting process for your feature request. There are 20 days until the voting process ends.

    Find more details about Angular's feature request process in our documentation.

  6. angular-robot commented on Nov 12, 2022

    @angular-robot
    Contributor

    Thank you for submitting your feature request! Looks like during the polling process it didn't collect a sufficient number of votes to move to the next stage.

    We want to keep Angular rich and ergonomic and at the same time be mindful about its scope and learning journey. If you think your request could live outside Angular's scope, we'd encourage you to collaborate with the community on publishing it as an open source package.

    You can find more details about the feature request process in our documentation.

  7. added
    feature: under consideration
    and removed on Nov 14, 2022
  8. pkozlowski-opensource commented on Nov 30, 2022

    @pkozlowski-opensource
    Member

    I think that we should start with the use-case first, as the notation of a host directive setting an input of its host component is ... surprising.

    @Harpush could you please share real-life use case where you need to set component inputs from a directive?

  9. added
    needs: clarification
    on Nov 30, 2022
  10. 26 remaining items

  11. wertzui commented on Sep 19, 2025

    @wertzui

    I'm running into the same problem when trying to add a directive to a 3rd party component.
    The 3rd party component switched from @Input() to input() and I can no longer set the values in my directive.

  12. Ketec commented on Sep 19, 2025

    @Ketec

    Still awaiting for a solution 😕

    Or at the very least, some confirmation or a sign that someone, somewhere has even acknowledged it on the angular side.

  13. removed
    needs: clarification
    feature: under consideration
    on Sep 19, 2025
  14. JeanMeche commented on Sep 19, 2025

    @JeanMeche
    Member

    The team is very well aware of this issue but is rather complex to tackle.
    Inputs should be set by the owner of the component.

    This has been stated before, you are not the owner of the component instance when you instantiate it via the template, Angular is. (so this excludes the idea of getting the ComponentRef).

    One way for a directive to set a value of its host component is to pass that value via template:

    @Component({
      selector: 'child',
      template: `val:{{val()}}`,
    })
    export class Child {
      val = input<number>(3);
    }
    
    @Directive({
      selector: '[foo]',
      exportAs: 'foo',
    })
    export class Foo {
      val = 5;
    }
    
    @Component({
      selector: 'app-root',
      imports: [Child, Foo],
      template: `<child [val]="foo.val" foo #foo=foo/>`,
    })
    export class App {}

    https://stackblitz.com/edit/angular-next-ws3xn86c?file=src%2Fmain.ts

  15. wertzui commented on Sep 19, 2025

    @wertzui

    After an extensive search, I found this issue #54987
    It mentions this helper function which worked for me and might help others too:

    import { SIGNAL } from '@angular/core/primitives/signals';
    
    export function setValueOfInputSignal<T, TransformT>(signal: InputSignal<T> | InputSignalWithTransform<T, TransformT>, value: T) {
      const node = signal[SIGNAL];
      signalSetFn(node, value);
      // There is node.applyValueToInputSignal(node, value); which just calls signalSetFn(node, value);
    }
  16. JeanMeche commented on Sep 19, 2025

    @JeanMeche
    Member

    @wertzui @angular/core/primitives is not a public package, the symbols it exposes should be considered private.

  17. wertzui commented on Sep 19, 2025

    @wertzui

    I know but currently it seems to be the only way do set the value.
    I'm not proposing to use it everywhere and everyone who is digging this deep should be well aware that it could break with any update.

    In the end I still hope to be able to set an InputSignal programatically in a future version.
    I don't see a reason why it should only be settable in a template or through model() which would be an anti-pattern as it "signals" that the the value should be changeable from inside the component.
    As for me changing input() to model() is not even an option as I'm working with a 3rd party component.

  18. Ketec commented on Sep 19, 2025

    @Ketec

    The team is very well aware of this issue but is rather complex to tackle. Inputs should be set by the owner of the component.

    This has been stated before, you are not the owner of the component instance when you instantiate it via the template, Angular is. (so this excludes the idea of getting the ComponentRef).

    One way for a directive to set a value of its host component is to pass that value via template:

    @component({
    selector: 'child',
    template: val:{{val()}},
    })
    export class Child {
    val = input(3);
    }

    @directive({
    selector: '[foo]',
    exportAs: 'foo',
    })
    export class Foo {
    val = 5;
    }

    @component({
    selector: 'app-root',
    imports: [Child, Foo],
    template: <child [val]="foo.val" foo #foo=foo/>,
    })
    export class App {}
    https://stackblitz.com/edit/angular-next-ws3xn86c?file=src%2Fmain.ts

    That kind of beats the purpose of directives that may preconfigure a lot of values - now every implementation has to do it over and over again. In some cases there could be 100-s of instances of "child" with a directive attached to it with a dozen inputs.

  19. Harpush commented on Sep 19, 2025

    @Harpush
    Author

    Well not the best solution as you have to redeclare all properties and can be done also theoretically using display: contents but one can do:

    Third party comp:

    @Component({
      selector: 'app-third-party',
      template: `
        <div>One: {{ one() }}</div>
        <div>Two: {{ two() }}</div>
        <div>Three: {{ three() }}</div>
      `,
    })
    export class ThirdParty {
      readonly one = input.required<string>();
      readonly two = input(0);
      readonly three = input<boolean>();
    }

    Wrapper around it:

    @Directive({
      selector: 'app-my-third-party',
    })
    export class MyThirdParty {
      private readonly vcr = inject(ViewContainerRef);
    
      readonly two = input.required<number>();
      readonly three = input<boolean>();
    
      constructor() {
        this.vcr.createComponent(ThirdParty, {
          bindings: [
            inputBinding('one', () => 'test'),
            inputBinding('two', this.two),
            inputBinding('three', this.three),
          ],
        });
        // NOTE: Only if you want to get rid of the empty `app-my-third-party` element in the DOM
        (this.vcr.element.nativeElement as HTMLElement).remove();
      }
    }

    Pros:

    1. Full control over inputs (same as wrapper component)
    2. No DOM nesting

    Cons:

    1. A bit complicated (more than wrapper)
    2. Different tag name when using it
    3. Need to redeclare all inputs that should be exposed as is
  20. mauriziocescon commented on Sep 19, 2025

    @mauriziocescon

    IMHO: good suggestion @Harpush!

    Some extra cons:

    • no attributes (class / style),
    • cannot set the selector... in (the rare?) case you have many.

    But overall, I guess it's the right starting point for big third-party components. I'm just not sure if createComponent has issues with hydration or not (see #61231).

  21. Ketec commented on Sep 19, 2025

    @Ketec

    In the end, these are all hacks to bypass limitations.
    Codebases will be full of these, in every variety in no time.

    And there are large codebases that get stuck in older angular versions, because they can't upgrade, because of third party libraries switching to signals.

    Refactoring is expensive.

    For example
    <kendo-multiselect myDirective myDataDirective />

    Where the directive handles anything from size, show/hide to event handlers, default settings, config, etc. To ensure the same look, common data and behaviour across the product.

  22. montella1507 commented on Sep 19, 2025

    @montella1507

    The team is very well aware of this issue but is rather complex to tackle. Inputs should be set by the owner of the component.

    This has been stated before, you are not the owner of the component instance when you instantiate it via the template, Angular is. (so this excludes the idea of getting the ComponentRef).

    One way for a directive to set a value of its host component is to pass that value via template:

    @component({
    selector: 'child',
    template: val:{{val()}},
    })
    export class Child {
    val = input(3);
    }

    @directive({
    selector: '[foo]',
    exportAs: 'foo',
    })
    export class Foo {
    val = 5;
    }

    @component({
    selector: 'app-root',
    imports: [Child, Foo],
    template: <child [val]="foo.val" foo #foo=foo/>,
    })
    export class App {}
    https://stackblitz.com/edit/angular-next-ws3xn86c?file=src%2Fmain.ts

    This is inversion of time..

    We would like to have situaion solved when:

    1. In T0, there exists component like Dropdown with [data]="" input.
    2. We sould like to have directives to set data to that input.

    etc.

  23. slavede commented on Oct 7, 2025

    @slavede

    Same here, I have a lot of directives that were injecting host component and setting its inputs based on the configuration given so I don't have to repeat myself 100+ times.
    Now, these inputs are not writable at all.
    Now it remains for me to stop updating Angular and 3rd party library I'm using, or to rewrite everything to wrap 3rd party lib into new component (issue is that it's used on 150+ places).

    By injecting component ref of hosted component, I would be able to use setInput at least.

    Btw, there is a similar scenario when having abstract class (inherited by other components) doing all of these as well. So I don't have to copy-paste 100+ same code into templates, rather just leaving it to abstract class to injec it via component ref.

    It's sad that issue is in backlog for 3 years already since it's preventing backwards compatibility in some cases

  24. MurhafSousli commented on Mar 21, 2026

    @MurhafSousli

    I am also a library author, it feels the the current solution is to use model but I don't want to expose outputs the user doesn't need!

    Right now my only options is to use a linkedSignal for each input I have!

    @Directive({
      selector: '[gallerySlot]',
      host: {
        '[style.z-index]': '3',
        '[style.grid-area]': 'position()',
        '[style.align-self]': 'align()',
        '[style.justify-self]': 'justify()',
      }
    })
    export class GallerySlot {
    
      readonly position = linkedSignal(() => this.gallerySlot());
    
      /**
       * Defines the docking position of the slot inside the gallery grid.
       * - 'center' (default): slot floats over the main slider.
       */
      readonly gallerySlot: InputSignalWithTransform<GalleryPosition, GalleryPosition | ''> = input<GalleryPosition, GalleryPosition | ''>('center', {
        transform: (value: GalleryPosition | '') => !value ? 'center' : value
      });
    
      readonly justify = linkedSignal(() => this.gallerySlotJustify());
    
      /**
       * Controls main-axis justification within the selected area.
       */
      readonly gallerySlotJustify: InputSignal<GalleryAlign> = input<GalleryAlign>('center');
    
      readonly align = linkedSignal(() => this.gallerySlotAlign());
      
      /**
       * Controls cross-axis alignment within the selected area.
       */
      readonly gallerySlotAlign: InputSignal<GalleryAlign> = input<GalleryAlign>('center');
    }

    Why can't I use a model and disable exposing an output?

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

Metadata

Metadata

Assignees

Labels

area: corefeature

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions