Skip to content

Allow host binding to feed inputs to host directives #50510

Open

Description

@jnizet

Which @angular/* package(s) are the source of the bug?

core

Is this a regression?

No

Description

If a directive (let's named it ReusableDirective) exposes a required input (foo), and is used as a host directive by another directive (ComposedDirective), then the compiler forces the composed directive to expose the required input.

This is problematic when the whole point of the composed directive is precisely to provide a default or computed value for the required input.

For example:

@Directive({
  selector: '[app-reusable]',
  standalone: true,
})
class ReusableDirective {
  @Input({ required: true }) foo!: string;

  // do something useful with foo here, but that's irrelevant
}

@Directive({
  selector: '[app-composed]',
  standalone: true,
  hostDirectives: [ReusableDirective],
})
class ComposedDirective {
  constructor(reusable: ReusableDirective) {
    reusable.foo = 'hello';
  }
}

Please provide a link to a minimal reproduction of the bug

https://stackblitz.com/edit/stackblitz-starters-85nxmu?description=An%20angular-cli%20project%20based%20on%20@angular/animations,%20@angular/common,%20@angular/compiler,%20@angular/core,%20@angular/forms,%20@angular/platform-browser,%20@angular/platform-browser-dynamic,%20@angular/router,%20core-js,%20rxjs,%20tslib%20and%20zone.js&file=src%2Fmain.ts&title=Angular%20Starter

Please provide the exception or error you saw

Required input 'foo' from host directive ReusableDirective must be exposed.

Please provide the environment you discovered this bug in (run ng version)

Angular CLI: 16.0.2
Node: 18.16.0
Package Manager: yarn 1.22.19
OS: darwin x64

Angular: 16.0.2
... animations, cli, common, compiler, compiler-cli, core, forms
... localize, platform-browser, platform-browser-dynamic, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1600.2
@angular-devkit/build-angular   16.0.2
@angular-devkit/core            16.0.2
@angular-devkit/schematics      16.0.2
@angular/cdk                    16.0.1
@schematics/angular             16.0.2
rxjs                            7.8.1
typescript                      5.0.4

Anything else?

This just hit me in a real situation: ng-bootstrap's typeahead directive's ngbTypeahead input is marked as requird in the latest version, and we have several custom fooTypeahead and barTypeahead directives which simply use ngbTypeahead as a host directive and provide this required input.

Activity

  1. jnizet commented on May 30, 2023

    @jnizet
    ContributorAuthor

    BTW, somewhat related to this issue, I haven't seen how, in the signals RFC, composed directives would be able to set inputs of their host directive if the host directive is a signal directive.

  2. crisbeto commented on May 31, 2023

    @crisbeto
    Member

    My thinking when I was introducing the error was that required inputs are members that the directive can't work without, similarly to how you have to specify every required property from an interface.

  3. Harpush commented on May 31, 2023

    @Harpush

    My thinking when I was introducing the error was that required inputs are members that the directive can't work without, similarly to how you have to specify every required property from an interface.

    If I can add my opinion - you are correct it can't work without. What's missing is the ability to provide it from the directive itself without exposing it (the hosting one).
    If I take the interface example - think of constructor. You must provide say A and B when newing a class. But I can extend this class and create a new constructor accepting nothing and pass A and B in super call. This "hides" the required parameters while still providing them as they are required to the base class. I can also expose them as required in the derived class if I want.

  4. kbrilla commented on May 31, 2023

    @kbrilla
    Contributor

    My thinking when I was introducing the error was that required inputs are members that the directive can't work without, similarly to how you have to specify every required property from an interface.

    If I can add my opinion - you are correct it can't work without. What's missing is the ability to provide it from the directive itself without exposing it (the hosting one). If I take the interface example - think of constructor. You must provide say A and B when newing a class. But I can extend this class and create a new constructor accepting nothing and pass A and B in super call. This "hides" the required parameters while still providing them as they are required to the base class. I can also expose them as required in the derived class if I want.

    this is exactly my opinion that I provided on PR introducing required inputs.

    Maybe a compromise would be to provide an option to mark required input as provided by directive/component.

    @Component({
      selector: 'admin-menu',
      template: 'admin-menu.html',
      hostDirectives: [{
        directive: MenuBehavior,
        inputs: ['menuId: id'],
        outputs: ['menuClosed: closed'],
        providedInputs:['requriedInput1'],
      }],
    })
    export class AdminMenu { 
      constructor() {
        inject(MenuBehavior, {self: true}).requriedInput1 = uuid();
      }
    }
    

    or

    @Component({
      selector: 'admin-menu',
      template: 'admin-menu.html',
      hostDirectives: [{
        directive: MenuBehavior,
        inputs: ['requriedInput1: {required: false, alias: undefined}], // or just not providing alias at all
        outputs: ['menuClosed: closed'],
      }],
    })
    export class AdminMenu { 
      constructor() {
        inject(MenuBehavior, {self: true}).requriedInput1 = uuid();
      }
    }
    

    this way we won't accidentally ignore required input but can handle providing them from within the host.

  5. added
    area: core
    on May 31, 2023
  6. modified the milestone: needsTriage on May 31, 2023
  7. crisbeto commented on Jun 7, 2023

    @crisbeto
    Member

    @jnizet could a potential workaround be to extend the directive that you want to apply as a host directive and apply the derived class? E.g. something like this:

    import {ReusableDirective} from 'some-lib';
    
    @Directive({
      selector: '[app-reusable]',
      standalone: true,
    })
    class MyReusableDirective extends ReusableDirective {
      @Input({ required: false }) foo!: string;
    }
    
    @Directive({
      selector: '[app-composed]',
      standalone: true,
      hostDirectives: [MyReusableDirective],
    })
    class ComposedDirective {}
  8. alwonder commented on May 26, 2024

    @alwonder

    Any updates of this? If i implement my inputs through signals, I have no options to assign them by default.

    It would be great to declare default value for the input somehow, along with alternative input name.

  9. 30 remaining items

  10. Ketec commented on Mar 31, 2026

    @Ketec

    Using host to bind to directive OR component inputs should have been there from the start of switching to signals.

    It really feels like library took 1 step forward and 5 steps backwards.

    There were no issues with a decade of @input() usage.

  11. Harpush commented on Apr 2, 2026

    @Harpush

    Coming back to this issue I must say it would make perfect sense like host bindings.
    Having a component with host binding and host directives seems like it was meant to be:

    @Component({
      selector: 'app-test',
      template: '...',
      styles: '...',
      host: {
        // Host bindings
        '[style.gap.px]': 'a()',
        '(click)': 'onClick($event)'
      },
      hostDirectives: [
        {
          directive: AppTooltip,
          // Host directive bindings
          inputs: {
            '[tooltip]': '`Value: ${a()}`',
          },
          outputs: {
            '(hovered)': 'onTooltipHovered()',
          }
        }
      ]
    })
    export class TestComponent {
      a = input.required<number>();
    
      onClick(e: MouseEvent) {
        console.log(e);
      }
    
      onTooltipHovered() {}
    }

    Which allows binding to host element and binding to a directive's input in the same way

  12. splincode commented on Apr 2, 2026

    @splincode
    Contributor

    Coming back to this issue I must say it would make perfect sense like host bindings. Having a component with host binding and host directives seems like it was meant to be:

    @component({
    selector: 'app-test',
    template: '...',
    styles: '...',
    host: {
    // Host bindings
    '[style.gap.px]': 'a()',
    '(click)': 'onClick($event)'
    },
    hostDirectives: [
    {
    directive: AppTooltip,
    // Host directive bindings
    inputs: {
    '[tooltip]': 'Value: ${a()}',
    },
    outputs: {
    '(hovered)': 'onTooltipHovered()',
    }
    }
    ]
    })
    export class TestComponent {
    a = input.required();

    onClick(e: MouseEvent) {
    console.log(e);
    }

    onTooltipHovered() {}
    }
    Which allows binding to host element and binding to a directive's input in the same way

    @crisbeto Hello, what do you think about?

  13. mauriziocescon commented on Apr 2, 2026

    @mauriziocescon

    @Harpush I think the idea behind host directives was simply to provide component-independent behavior that can be dropped in anywhere — completely decoupled from the component it is applied to (inputs belong to the consumer and cannot be set from within the component).

    So, having a directive on the host that depends on component values is fundamentally out of scope.

    That said, the whole host-directives dance is very confusing. In my opinion, the real culprit is the host itself: remove it from the equation and everything becomes simple and reasonable again.

    Svelte has something similar to directives (called attachments). Here are two examples of buttons with tooltips that illustrate a cleaner approach:

    • no host, selectors, or similar concepts,
    • directives can be passed as inputs,
    • directives can be applied conditionally,
    • data is always derived (typically from inputs),
    • easy to follow and reason about,
    • clear data ownership.

    As always, just a different point of view. ☮️

    <script lang="ts">
    	import ButtonWithTooltip from './ButtonWithTooltip.svelte';
    	import Button from './Button.svelte';
    
    	import { tooltip } from './tooltip.svelte';
    	
    	let consumerLabel = $state('Consumer label');
    </script>
    
    <!-- tooltip-dir passed as an input -->
    <Button {@attach tooltip(consumerLabel)}> Btn </Button>
    
    <!-- your example: tooltip-dir attached inside ButtonWithTooltip, content = consumerLabel -->
    <ButtonWithTooltip {consumerLabel}> Btn with tooltip </ButtonWithTooltip>
    // ButtonWithTooltip
    
    <script lang="ts">	
    	import { tooltip } from './tooltip.svelte';
    
    	// inputs
    	const { children, consumerLabel, ...rest } = $props();
    
    	// computed	
    	const derivedLabel = $derived(`${consumerLabel} with extra text`);
    	const enabled = $derived(consumerLabel !== 'disable');
    </script>
    
    <! -- conditionally adding tooltip-dir -->
    <button 
    	{@attach enabled && tooltip(derivedLabel)}
    	{...rest}>	
    	{@render children?.()}
    </button>
    // Button
    
    <script lang="ts">
    	// inputs
    	const { children, ...rest } = $props();
    </script>
    
    <!-- `rest` includes tooltip-dir -->
    <button {...rest}>
    	{@render children?.()}
    </button>

    https://svelte.dev/playground/1556ba91167b4f70a7d0dbc9b29c3a58?version=5.55.1

  14. waterplea commented on Apr 3, 2026

    @waterplea
    Contributor

    I think the idea behind host directives was simply to provide component-independent behavior that can be dropped in anywhere — completely decoupled from the component it is applied to (inputs belong to the consumer and cannot be set from within the component).

    This premise is completely and utterly wrong. The "component-independent" behavior that can be dropped in anywhere is a directive. A HOST directive is a HOST-dependent behavior and consumer is THE HOST.

    In my opinion, the real culprit is the host itself: remove it from the equation and everything becomes simple and reasonable again.

    lol, that's what we had BEFORE hostDirectives. Host was removed from the equation and we had directives.

    Once again, there's no philosophical debate to be had here. This is what we need.

  15. Harpush commented on Apr 3, 2026

    @Harpush

    I think adding directive input/output bindings compliments the existing ways to apply directives.
    Given this directive:

    @Directive({ selector: '[appTester]' })
    export class TesterDirective {
      value = input.required<number>()
    }

    We have two ways to apply the directive to a component:
    In the HTML:

    <app-comp appTester [value]="8" />

    Using create component:

    createComponent(CompComponent, {
      environmentInjector: inject(EnvironmentInjector),
      directives: [{ type: TesterDirective, bindings: [inputBinding('value', () => 8)] }],
    })

    I think it only makes sense to allow the same bindings support for host directives:

    @Component({
      selector: 'app-comp',
      template: '',
      hostDirectives: [
        {
          directive: TesterDirective,
          bindings: {
            '[value]': '8',
          }
        },
      ],
    })
    export class CompComponent {}
  16. EmmanuelRoux commented on Apr 3, 2026

    @EmmanuelRoux
    Contributor

    ⬆️ this is the way (and should be upvoted)

  17. jermowery commented on Jun 5, 2026

    @jermowery
    Contributor

    Is it possible to get an official comment or triage from the Angular team on this? I (internal user) would also like to see the ability to set the input values of a host directive, and it is important to know if we should plan for this never being a thing

  18. crisbeto commented on Jun 6, 2026

    @crisbeto
    Member

    I'll bring this up again in our next sync. We didn't do this before, because it likely would've resulted in a bunch of "changed after checked errors". With signals it might not be a problem though.

  19. waterplea commented on Jun 6, 2026

    @waterplea
    Contributor

    I'll bring this up again in our next sync. We didn't do this before, because it likely would've resulted in a bunch of "changed after checked errors". With signals it might not be a problem though.

    Please prioritize this, it's a very needed feature, it really isn't a problem with signals anymore. We were using a utility tool to work around it for a very long time, it works like charm, getting a first class official support would be an improvement we'd love to have. What we have is basically this:

    function binding<T, G>(what: ProviderToken<T>, key: G extends keyof T, value: T[G] | Signal<T[G}>)

    And we would either feed it static values, or computed signals or just signals that we would manually set later. It's insanely powerful decomposition tool. I would love to be able to just write this in host.

    There are probably some arguments to be had about cases where multiple bindings happen. If it was up to me I would allow this, as it might be a common case where you want to just feed static initial values for a host directive from your component and still allow people to feed values later via exposed inputs if they want. I wouldn't want it to through at runtime with something like "multiple bindings to the same input is not allowed". I get that it can cause sync issues but I would love framework to trust me with handling those instead of locking me out of it completely as it was with double directive matching for years.

  20. robmanganelly commented on Jul 28, 2026

    @robmanganelly

    EDIT to add solution: credits to the spartan team

    This is an important feature, but it seems (based on some comments) like it could open the door for other problems.
    Could anyone reply with examples of what could go wrong if we make it happen?
    Are we getting into a rabbit hole of any kind here?


    For the people (like me) coming to find a solution to a problem, check the following code (adapted from spartan)

    The problem, we want to create a directive based on HlmButton, but providing a default variant

    1. actions wrapper directive
      this one provides a button configuration that is used by the HlmButton directive to set variant and size.
      any instance of HlmButton inside this directive will have 'outline' variant.
      You can provide the config at the directive level if you want, this is just to make sure that every child in the actions starts as outline buttons
    @Directive({
        providers: [provideBrnButtonConfig({ variant: 'outline'})],
        selector: '[hlmMultiFilterActions],hlm-multi-filter-actions'
    })
    export class HlmMultiFilterActions {
        constructor(){
            classes(()=>'flex gap-2 ')
        }
    }
    1. The child directive
    @Directive({
      hostDirectives: [
        {
          directive: HlmButton,
          inputs: ['variant', 'size'],
        },
      ],
      selector: '[hlmMultiFilterActionClear]',
    })
    export class HlmMultiFilterActionClear {}
    1. usage
      When you use the Clear directive inside hlm-multi-filter-actions the provider is setting outline variant on its HlmButton
    <hlm-multi-filter-actions>
            <button hlmMultiFilterActionAdd><ng-icon name="lucideListFilterPlus"></ng-icon></button>
            <button hlmMultiFilterActionClear>
                <ng-icon name="lucideFilterX"></ng-icon>
            </button>
     </hlm-multi-filter-actions>
    Image
  21. waterplea commented on Jul 29, 2026

    @waterplea
    Contributor

    @robmanganelly the way we in Taiga UI got around this particular issue that you have is all our components have options DI token that defines default input values and then directives like yours can provide this token with defaults override (through a helper that takes Partial object and injects skipSelf token to spread it for the current value higher up the DI hierarchy). That's not to say the requested feature is not necessary, we also want it very much, just an example how to solve this exact situation with current API.

  22. robmanganelly commented on Jul 30, 2026

    @robmanganelly

    Yes. Taiga UI is a first class lib, and DI solutions like the one you mentioned are clean and idiomatic, with the sole downside of requiring more moving parts.
    However the original question still stands
    Could a feature like this cause performance issues or open the door for abuse?

  23. nud commented on Oct 19, 2026

    @nud

    I ran into the same problem today. There is basically no problem in setting up inputs of directives when using @Input, but it won't work if you're using input(), especially when using third party directives that you can't really modify as a workaround.

  24. vampirsoft commented on Nov 29, 2026

    @vampirsoft

    I'll add my two cents: this is a truly sought-after feature, and it's been highly anticipated for many versions now. We're seeing the need for it too, and we've started writing our own design system.

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: corecore: host directives

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions