How to implement generic classes in components?

Discussão em 'Angular' iniciado por Freek Wiekmeijer, Dezembro 17, 2024.

  1. Right now the app contains several near-identical components. Each of them is basically a list view of data models with a search bar to filter the list.

    For each of these components:

    • Input is the initially selected item;
    • Output is a select(item) event emitter;
    • The component encapsulates an API call to retrieve the list of items.

    So their functionality is practically identical. Load an array of models from the API, render them in a list view, offer a sarch bar for filtering of the list and expose the selected item from the list to the parent component.

    Use case:

    ...
    <app-customer-search [initialSelection]="myCurrentCustomer"
    (select)="onSelectCustomer($event)>
    </app-customer-search>
    ...


    ...
    class CustomerComponent {
    ...
    initialSelection = input<Customer>();
    select = output<Customer>();
    ...
    }


    and:

    ...
    <app-contract-search [initialSelection]="myCurrentContract"
    (select)="onSelectContract($event)>
    </app-contract-search>
    ...


    ...
    class ContractComponent {
    ...
    initialSelection = input<Contract>();
    select = output<Contract>();
    ...
    }


    What I would like to achieve is to rewrite the two components into one, i.e.

    <app-select-item [modelClass]="Customer"
    [apiFunc]="loadCustomers"
    [initialSelection]="myCurrentCustomer"
    (select)="onSelectCustomer($event)>
    </app-select-item>


    and

    <app-select-item [modelClass]="Contract"
    [apiFunc]="loadContracts"
    [initialSelection]="myCurrentContract"
    (select)="onSelectContract($event)>
    </app-select-item>


    In other languages like C# one might use generic classes. Like

    class ItemSelectComponent<T> where T: class, new()
    {
    ...
    }


    Assuming we call the model class T, I would like to type the input as input<T>(), the API function as Func<Observable<Array<T>>> and teh output as EventEmitter<T>.

    Is there any way to do this in Typescript?

    Continue reading...

Compartilhe esta Página