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

时间:2018-03-12 02:06:13

标签: angular typescript components

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

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}}不会显示在组件中选择的值。

1 个答案:

答案 0 :(得分:4)

select.component.html

你应该使用[值]而不是[ngValue]: [ngValue] =&gt; [数值]

<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

并添加public selectedValue;

export class PfSelectComponent implements OnInit {

  public selectedValue;
  constructor() { }

  ngOnInit() {
  }

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

我用

测试了这个
options = [
    {
      value: 1,
      name : "1"
    },
    {
      value: 2,
      name : "2"
    },
    {
      value: 3,
      name : "3"
    }
  ]

效果很好:))