1

I coded a dropdown with two option inside: english and french. But for each option I need to call a different function. My code is in HTML :

 <select (click)="myFuncEnglish()">
    <option value="EN">English</option>
    <option value="FR">France</option>
</select>

And for Angular is:

myFuncEnglish() {
    console.log('function called is english');
  }`

Can you help me please to know how can I code different function for the different options, and to display when I click on french "function called is french", and when I click on english "function called is english".

Kuldeep Bhimte
  • 961
  • 1
  • 10
  • 25
shtb2708
  • 49
  • 7

3 Answers3

1

I guess, you don't need to call two functions. You need to pass the selected value as the function argument and check the value in the function body to console log your message.

HTML

<select (ngModelChange)="myFuncEnglish($event)"  [(ngModel)]="lang">
    <option value="EN">English</option>
    <option value="FR">France</option>
</select>

Component

myFuncEnglish(lang) {
    if(lang === 'FR'){
      console.log('function called is french');
    } else {
      console.log('function called is english');
    }
}

See a working example here

Community
  • 1
  • 1
Kuldeep Bhimte
  • 961
  • 1
  • 10
  • 25
0

Do it onchange insted, on Angular i think it is ng-change="funcEnglish()"

Then on funcEnglish validate the item.value to know you what to do.

function funcEnglish(item) {
    console.log('function called is '+ item.value);
  }
 <select onchange="funcEnglish(this)">
    <option value="Empty">None</option>
    <option value="EN">English</option>
    <option value="FR">France</option>
</select>
Alen.Toma
  • 4,684
  • 2
  • 14
  • 31
  • I'm sorry but it displays nothing without errors and I don't know why, and I used ng-charge – shtb2708 Feb 07 '19 at 23:47
  • i really dont know Angular very much but i think that you should remove function and have only `funcEnglish` i think. – Alen.Toma Feb 07 '19 at 23:49
  • yes It's how I coded with your help but It still doesn't work – shtb2708 Feb 07 '19 at 23:50
  • Really cant help you with that. i have never worked with Angular before. but i think that there is something wrong with your component. see https://docs.angularjs.org/api/ng/directive/ngChange to know how ng-change work – Alen.Toma Feb 08 '19 at 00:06
0

Another way is not using ngModel just use change event.

HTML

<select (change)="myFuncEnglish($event)">
    <option value="EN">English</option>
    <option value="FR">France</option>
</select>

Typescript

myFuncEnglish(event: any) {
    if(event.value === 'FR'){
      console.log('function called is french');
    } else {
      console.log('function called is english');
    }
}
Nandy Yray
  • 51
  • 2