Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

right way to call a function after selected option. Angular 4

Hello I need to call a function after one of the options is selected.

which is the best way to do it? im using angular4.

modo(){
  // if modo 1 is selected do something.
  // if modo 2 is selected do something.
  // if modo 3 is selected do something.
}
<label>Modo :</label>
<select id="selectid" class="form-control-mb-12">
   <option value="mod1">MODO 1</option>
   <option value="mod2">MODO 2</option>
   <option value="mod3">MODO 3</option>
</select>
like image 545
Ixam Deirf Avatar asked Jul 12 '17 15:07

Ixam Deirf


1 Answers

You can use the change event handler as folows, which passes the selected value to the handler:

<select id="selectid" class="form-control-mb-12" (change)="modo($event.target.value)">
   <option value="mod1">MODO 1</option>
   <option value="mod2">MODO 2</option>
   <option value="mod3">MODO 3</option>
</select>

modo(value: string){
  switch(value) {
    case "mod1":
       // if modo 1 is selected do something.
       break;
    case "mod2":
       // if modo 2 is selected do something.
       break;
    case "mod3":
       // if modo 3 is selected do something.
       break;
  }
}

You could also bind the value of the select to a property on your model using [(ngModel)] then you wouldn't need to pass the value to the handler as your model would already have it.

https://angular.io/api/forms/NgModel

like image 194
James Gaunt Avatar answered Sep 20 '22 09:09

James Gaunt