In Angular, is there a way for a component's generic type to be used as a child directive's...

Discussão em 'Angular' iniciado por NFrank, Novembro 12, 2024.

  1. NFrank

    NFrank Guest

    I've been searching around for this for a while now and I'm not sure if I'm just not asking the question the right way or what I'm trying to do isn't possible (yet? we didn't always have ngTemplateContextGuard, so maybe someday?).

    Generally speaking, what I'm trying to do is use a generic type parameter on a component to drive context type guards for multiple child template directives.

    So something along these lines:

    <my-table [dataItems]="employees">
    <ng-template [myTableColumn] let-item="dataItem" [header]="'Name'">
    {{dataItem.EmployeeName}}
    </ng-template>
    <ng-template [myTableColumn] let-item="dataItem" [header]="'Date of Hire'">
    {{dataItem.HireDate}}
    </ng-template>
    </my-table>


    ...
    export class MyTableComponent<TData> {
    ...
    public dataItems: TData[];
    ...
    }


    With dataItem in the templates being type-checked based on TData.

    I've started using this solution (https://github.com/angular/angular/issues/28731#issuecomment-1729612396), which I like for standalone ng-template blocks, but it seems clunky in cases where I've sort of already specified the type (as in the above my-table example) and also where my component has multiple child templates.

    Note that I'm also aware of this example (https://stackoverflow.com/a/77957658/144473), which is close, but I'm trying to get the information to flow the other direction (parent component to child directive), and I also don't want to have to specify something on multiple templates.

    Can anyone point me in the direction of an example that does something like this or information that might point me in the right direction? Thanks.

    Continue reading...

Compartilhe esta Página