如何在Angular Material垫选择中获取值和文本

Iba*_*408 4 angular-material2 angular

我需要获取垫选择的数据,具体是文本及其值。到目前为止,这就是我实施Mat-select的方式。

<mat-select placeholder="Transaction Type" (selectionChange)="selected($event)" formControlName="TransactionTypeID">
    <mat-option *ngFor="let t of transactionTypes" [value]="t.TransactionTypeID">
        {{t.TransactionType}}
    </mat-option>
</mat-select>
Run Code Online (Sandbox Code Playgroud)

这就是我在.ts文件中获取值的方式: this.formDetail.get('TransactionTypeID').value,

这是我尝试获取文本或“ t.TransactionType”的尝试:

selected(event: MatSelectChange) {
    console.log(event);
}
Run Code Online (Sandbox Code Playgroud)

你能告诉我怎么做吗?谢谢。

小智 14

要完成前面的答案,可以使用MatOption的viewValue。Angular 7编译器也想知道event.source.selected应该是数组还是单个对象。

selected(event: MatSelectChange) {
    const selectedData = {
        text: (event.source.selected as MatOption).viewValue,
        value: event.source.value
    }
    console.log(selectedData);
}
Run Code Online (Sandbox Code Playgroud)


Jav*_*SKT 9

通过正常更改事件,您可以得到如下所示的值

在.html文件中

<mat-select placeholder="Transaction Type" (change)="selected($event)" formControlName="TransactionTypeID">
    <mat-option *ngFor="let t of transactionTypes" [value]="t.TransactionTypeID">
        {{t.TransactionType}}
    </mat-option>
</mat-select>
Run Code Online (Sandbox Code Playgroud)

在.ts文件中

selected(event) {
    let target = event.source.selected._element.nativeElement;
    let selectedData = {
      value: event.value,
      text: target.innerText.trim()
    };
    console.log(selectedData);
}
Run Code Online (Sandbox Code Playgroud)

  • 不好 首先,从材料7开始,“更改”事件现在为“ selectionChange”。其次,您不能访问`_element`。@rodo的解决方案是正确的答案 (3认同)

nip*_*hka 5

它可以轻松地使用此代码。

HTML

 <mat-select value="option1" (selectionChange)=changeRatio($event)>
                <mat-option value="option0">Free Selection</mat-option>
                <mat-option value="option1">1 : 1.5 (Recommended)</mat-option>
 </mat-select>
Run Code Online (Sandbox Code Playgroud)

角度TS

  changeRatio(event: MatSelectChange) {
    console.log(event.value);
  }
Run Code Online (Sandbox Code Playgroud)