Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i get selected value from a select component

How can I get the selected value from a select component?

select.component.ts:

export class PfSelectComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  @Input() options : Array<Object>;

}

select.component.html

<select [(ngModel)]="selectedValue" id="exampleFormControlSelect1" class="form-control">
  <option *ngFor="let option of options" [ngValue]="option.value">{{option.name}}</option>
</select>

select value: {{selectedValue}}

{{selectValue}} does not show the value selected in the component.

like image 283
Rafael Augusto Avatar asked Jan 29 '23 12:01

Rafael Augusto


1 Answers

select.component.html

You shoud use [value] not [ngValue] : [ngValue] => [value]

<select [(ngModel)]="selectedValue" id="exampleFormControlSelect1" class="form-control" >
  <option *ngFor="let option of options" [value]="option.value">{{option.name}}</option>
</select>

select value: {{selectedValue}}

select.component.ts

and add public selectedValue;

export class PfSelectComponent implements OnInit {

  public selectedValue;
  constructor() { }

  ngOnInit() {
  }

  @Input() options : Array<Object>;
}

I tested this with

options = [
    {
      value: 1,
      name : "1"
    },
    {
      value: 2,
      name : "2"
    },
    {
      value: 3,
      name : "3"
    }
  ]

It works well :)

like image 59
Jihoon Kwon Avatar answered Jan 31 '23 22:01

Jihoon Kwon