首页 > 解决方案 > 如何获得垫选择的价值

问题描述

我有一个垫子选择,我想获取用户选择的下拉列表的值。我怎样才能做到这一点?另外,如果用户通过重新选择来更改值,我该如何捕获它。html代码:

<mat-form-field appearance="fill">
              <mat-label>Country</mat-label>
              <select matNativeControl formControlName='country' (change)="selected($event)">
                <option disabled>Select</option>
                <option *ngFor="let option of country" [value]="option">{{option}}</option>
              </select>
            </mat-form-field>

打字稿代码:

country = ['au', 'kr', 'gb'];

标签: javascripthtmltypescript

解决方案


检查此沙箱:https ://stackblitz.com/edit/angular-1k7ykb-cfmaq7?file=app%2Fselect-value-binding-example.ts

ngModel 将选择器的值与 TS 文件中的值绑定。您不需要单独的更改处理程序

在您的 HTML 中

<mat-select [(ngModel)]="selected">
    <mat-option *ngFor="let o of arr" [value]="o">{{o}}</mat-option>
</mat-select>
 <div> Seleced: {{selected}}</div>

在你的 TS 文件中使用你的数组(我们甚至可以设置默认值)

export class SelectValueBindingExample {

  selected: string;

  arr: string[] = [];

 constructor() {
    this.arr.push("au");
    this.arr.push("kr");
    this.arr.push("gb");
    this.selected = 'gb';
  }
}

推荐阅读