htmlangulartypescript1.7

How to call different function on selecting different option from drop down in angular 5


Many number of drop downs are to be used. Requirement is when a option from drop down is selected corresponding custom function is need to be called, as in below what should be in place of opt.mtd as its not working

html

<li class ="dropdown"> 
<div id="name">Activities</div>
<li *ngFor="let opt of activityList">
<a (click)=opt.mtd>{{opt.name}}</a>
</li>
</li>

Component

export class..{

activityList=[{mtd:"getActivity1()", name:"cycling"},
{Mtd:"getActivity2()", name:"swimming"}]

Solution

  • In your example the value of mtd is just a string. You need to pass the actual function.

    function getActivity1() {...};
    function getActivity2() {...};
    
    activityList=[
        {mtd: getActivity1, name:"cycling"},
        {mtd: getActivity2, name:"swimming"}
    ]
    

    Also, remove the () after the assignment, you don't want to execute the functions here, you just want to assign them to use them later in (click).