Domagoj Hamzic
Domagoj Hamzic

Reputation: 361

Call a specific function which is defined in an Array of buttons from an HTML *ngFor statement

So, I defined an array of button properties:

locationButtons: IButton[] = [
    {
      label: 'Customer-Hierarchy.LocationActions.SiteVisitButton',
      disabled: true,
      code: ButtonCode.SiteVisit,
      redirectUrl: 'this.onSiteVisitClick()'
    },
    {
      label: 'Customer-Hierarchy.LocationActions.ServiceInstallationButton',
      disabled: true,
      code: ButtonCode.ServiceInstallation,
      redirectUrl: 'this.onServiceInstallClick()'
    }
];

I want to call a function defined inside a redirect Url prop when the user clicks a button.

<div *ngFor="let item of locationButtons">
    <button ngbDropdownItem [disabled]=item.disabled
        (click)=item.redirectUrl>
        {{item.label | translate}}
    </button>
</div>

I tried with:

redirectUrl: this.onSiteVisitClick

.HTML

<button [disabled]=item.disabled (click)=item.redirectUrl()>
</button>

But when I want to call the function inside of item.redirectUrl() function I get this error: this.testFunction is not a function. Code example:

onSiteVisitClick() {
   this.testFunction();
}
testFunction() {
    alert('Test');
}

Upvotes: 0

Views: 189

Answers (1)

akotech
akotech

Reputation: 2274

You can assign the redirectUrl properties to the appropriate method:

locationButtons: IButton[] = [
    {
      ...
      redirectUrl: this.onSiteVisitClick
    },
    {
      ...
      redirectUrl: this.onServiceInstallClick
    }
];

An then bind the click event to the method call.

<div *ngFor="let item of locationButtons">
    <button ngbDropdownItem [disabled]="item.disabled"
        (click)="item.redirectUrl()">
        {{item.label | translate}}
    </button>
</div>

cheers

Upvotes: 1

Related Questions