Home > Mobile >  Angular - How to pass back value from submit button to call a function?
Angular - How to pass back value from submit button to call a function?

Time:06-12

I have a html which has the following dropdown list

    <select>
      <option *ngFor="let t of items" value="t">
          {{ t }}
        </option>
    </select>

Now I also have a submit button on the same page

<button type="button" (click)="selectedValue()" >
  Submit
</button>

What I would like to do is to take the value user has selected. I am assuming it is stored in "t" and then pass it in a function

 selectedValue() {
    // would like to call 
updateValue(t) { }
    
    
      }

Something like that.. Not sure where to being from the html back to the ts and then calling a function which will update value and give a 200ok result from http call.

CodePudding user response:

Work with ngModel with two-way binding.

While for the option either use [value] directive or value="{{ t }}". As currently, each option is holding the value with "t" string which is incorrect.

<select [(ngModel)]='selectedOption'>
  <option *ngFor="let t of items" [value]="t">
      {{ t }}
    </option>
</select>
selectedOption: string;

selectedValue() {
  this.updateValue(this.selectedOption);
}

updateValue(t) { 
  console.log(t);
}

Sample StackBlitz Demo

  • Related