Angular Directive Composition: How to Pass a Computed Input?

Discussão em 'Angular' iniciado por Matan Shushan, Abril 3, 2025.

  1. I have a custom directive (myDirective) that composes a third-party directive (ThirdPartyDirective) via the hostDirectives property in Angular.

    I’m passing several inputs directly, but one of them needs to be computed in my directive before being passed along. Specifically, I have a read-only signal (time) from which I compute a dateFromTime value. I’d like to use dateFromTime as an input in ThirdPartyDirective.

    The challenge is that ThirdPartyDirective expects a signal input, and I cannot simply assign a new signal in an effect. How can I handle computed inputs in this scenario so that dateFromTime is properly passed to ThirdPartyDirective?

    @Directive({
    selector: '[myDirective]',
    standalone: true,
    hostDirectives: [
    {
    directive: ThirdPartyDirective,
    inputs: [
    'name',
    'age',
    'date' // <-- I'd like this to be based on a computed value
    ]
    }
    ]
    })
    export class MyDirective {
    readonly time = input.required<number>();
    dateFromTime = computed(() => new Date(this.time()));

    // I'd like to pass dateFromTime as 'date' to ThirdPartyDirective
    }


    Is there a recommended approach passing a computed value into the host directive’s input?

    Any tips, patterns, or best practices you can share would be greatly appreciated!

    Continue reading...

Compartilhe esta Página