Marcel
Marcel

Reputation: 91

How to implement Buttons depending on a list?

I want to generate and display as many buttons depending on the number of elements in my list. Can someone tell me how I can implement that?

Currently it is hardcoded like the below code. But often I only have a list with only button 1 and 2. And then I dont need the button 3 and button 4.

Thanks for your help!

list=[button1, button2, button3, button4]

<div class="tabs_item_categories">
    <button class="tab_item_category" (click)="button1_active()">
         Button1
    </button>
    <button class="tab_item_category" (click)="button2_active()">
         Button2
    </button>
    <button class="tab_item_category"(click)="button3_active()">
         Button3
    </button>
    <button class="tab_item_category" (click)="button4_active()">
         Button4
    </button>
</div>

Upvotes: 0

Views: 57

Answers (1)

Ludevik
Ludevik

Reputation: 7254

You iterate with *ngFor structural directive in angular:

<div class="tabs_item_categories">
    <button class="tab_item_category" 
            *ngFor="let buttonConfig of buttonConfigs" 
            (click)="buttonConfig.onClick()">
        {{buttonConfig.label}}
    </button>
</div>

and in your typescript:

buttonConfigs = [
    {
        label: 'Button 1',
        onClick: this.doSomethingOnButton1Click
    },
    ...
];

doSomethingOnButton1Click is lambda in the component.

Upvotes: 3

Related Questions