0

I have a question regarding how to best approach a generic component that can be reused. I have tried to simplify the case as much as I can.

Say we create an angular component custom-list, that takes an input of ListItem[].

The HTML, very simple, can be something like:

<div>
    <ul>
        <li 
            *ngFor="let item of this.itemList"
            (click)="this.itemClicked(item)"
        >
        {{ item.title }}
        </li>
    </ul>
</div>

Now, I have a question regarding the type. I define ListItem as follows:

export interface ListItem {
    title: string;
    innerElement: any;
}

This allows me to create custom lists from objects of any types and save the object as a reference if I wish to access it later. Say that:

interface Mailbox {
    mailboxName : string
    mailboxEmails: number
}

const mailboxes : Mailbox[] = [
    {
        mailboxName: "Mailbox one",
        mailboxEmails: 43,
    },
    {
        mailboxName: "Mailbox two",
        mailboxEmails: 3
    }
]

this.itemList: ListItem[] = mailboxes.map(x => ({title: x.mailboxName, innerElement: x}));

Now, the problem here, is that I lose the type Mailbox when I try to access the items in list, due to innerElement being of the type any. I'd really like to keep that. How would I go about designing such a pattern?

Tikki
  • 179
  • 1
  • 10
  • 1
    Might be overkill in some cases but take a look at this: https://stackoverflow.com/questions/37225722/ng-content-select-bound-variable or that: https://stackoverflow.com/questions/39292195/angular2-html-inside-a-component You can provide custom html and render that in your custom list for any type of data you require. – Fussel Nov 16 '22 at 12:54

1 Answers1

0

I think I may have a solution to the issue;

export interface ListItem<T> {
    title: string;
    innerElement: T;
}

It requires the developer to define the type of the innerElement - but that might be the best way to do it? :)

This raises some issues on the component such as @Input- how would I transfer the input type here?

    @Input() items: Array<ListItem<TYPE REQUIRED HERE>> = [];
Tikki
  • 179
  • 1
  • 10