如何从选择组件中获取选择的值

Raf*_*sto 4 components typescript angular

如何从选择组件中获取选择的值?

select.component.ts:

export class PfSelectComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  @Input() options : Array<Object>;

}
Run Code Online (Sandbox Code Playgroud)

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}}
Run Code Online (Sandbox Code Playgroud)

{{selectValue}}不显示在组件中选择的值。

Jih*_*won 7

select.component.html

您应该使用[value]而不是[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}}
Run Code Online (Sandbox Code Playgroud)

select.component.ts

并添加public selectedValue;

export class PfSelectComponent implements OnInit {

  public selectedValue;
  constructor() { }

  ngOnInit() {
  }

  @Input() options : Array<Object>;
}
Run Code Online (Sandbox Code Playgroud)

我用

options = [
    {
      value: 1,
      name : "1"
    },
    {
      value: 2,
      name : "2"
    },
    {
      value: 3,
      name : "3"
    }
  ]
Run Code Online (Sandbox Code Playgroud)

它很好用:)