角度7和角度材料如何获取mat-select的选定选项文本而不是其值

时间:2018-12-06 13:52:22

标签: angular angular-material angular-reactive-forms angular7

我需要获取材料下拉列表<mat-select>的选定文本而不是其值:

<ng-container matColumnDef="fr">
        <th mat-header-cell *matHeaderCellDef> Family Rel. </th>
        <td mat-cell *matCellDef="let element; let i = index;">
          <div [formGroupName]="i">
            <mat-form-field color="warn" appearance="outline">
              <mat-label>Family Relation</mat-label>
              <mat-select #familyRelation (selectionChange)="onChange(element, i, 'hh')" id="family_relation"
                formControlName="fr" placeholder="Family Relation">
                <mat-option *ngFor="let familyRelation of familyRelationArray;" [value]="familyRelation.family_relation_id">
                  {{familyRelation.family_relation_type}}
                </mat-option>
              </mat-select>
            </mat-form-field>&nbsp;
          </div>
        </td>
      </ng-container>

这就是我想要做的事情:

@ViewChild('familyRelation') familyRel: ElementRef;

在下拉列表的更改选择上:

onChange(data, i, type) {
    let c = this.familyRel.nativeElement.innerText;
    console.log(c)
}

我遇到以下错误:

  

错误TypeError:无法读取未定义的属性'innerText'       在

当我删除innerText时,控制台值为:

  

未定义

stackblitz中可以看到我需要的,如果我选择了Parent,我想将Parent放入变量,而不是1,它是其{ {1}}。

请注意,id中的elementihh在该函数的后面使用,所以现在就算了吧。

6 个答案:

答案 0 :(得分:7)

很抱歉迟到了派对。阅读以上所有答案我真的很震惊...

该解决方案比任何提出的答案都要容易和直接得多,因为select组件只是将所选模型作为selectionChange参数的一部分传递。

但是首先,对您的示例进行一些更正。您已经声明了接口,因此请使用它:

export interface FamilyRelation {
    id: number;
    type: string;
}

因此,在您的构造函数中:

 constructor() {
    this.familyRelationArray=[
    {
      id: 1,
      type: 'Parent'
    },
    {
      id: 2,
      type: 'Sister'
    }
  ]
}

而不是您放入StackBlitz中的内容...然后您的视图将变为:

<mat-select (selectionChange)="onChange($event)" id="family_relation" placeholder="Family Relation">
    <mat-option *ngFor="let familyRelation of familyRelationArray;" [value]="familyRelation.id">
        {{familyRelation.type}}
    </mat-option>
</mat-select>

每个垫子选项都不需要(click)处理程序,因为这是不必要的,如果有很多选择项,则可能导致性能问题。现在,在控制器上:

onChange(ev: any) {
   let optionText = ev.source.selected.viewValue;
   console.log(optionText);
}

,或者,如果愿意,还可以输入类型变量:

onChange(ev: MatSelectChange) {
   let optionText = (ev.source.selected as MatOption).viewValue;  //use .value if you want to get the key of Option
   console.log(optionText);
}

但不要忘记进口...

import { MatSelectChange } from '@angular/material/select';
import { MatOption } from '@angular/material/core';

答案 1 :(得分:3)

您可以添加索引以使用mat-option循环,然后将其传递给onChange()方法,它将允许您从数组中获取选定的元素。

<mat-select #familyRelation (selectionChange)="onChange($event.value, element, i, 'hh')" id="family_relation" placeholder="Family Relation">
    <mat-option *ngFor="let familyRelation of familyRelationArray; let i=index" [value]="i">
        {{familyRelation.family_relation_type}}
    </mat-option>
</mat-select>

 onChange(index, data, i, type) {
    console.log(this.familyRelationArray[index].family_relation_type);
}

您在这里有更新代码:link

答案 2 :(得分:2)

使用compareWith

 <mat-select #familyRelation [compareWith]="compareFn" id="family_relation"  formControlName="fr" placeholder="Family Relation">
      <mat-option *ngFor="let familyRelation of familyRelationArray;" [value]="familyRelation.family_relation_id">
          {{familyRelation.family_relation_type}}
     </mat-option>
 </mat-select>


compareFn(data1 , data2){

}

compareWith侦听“ change”事件,因为在Firefox中没有为选择触发“ input”事件。 DOC

答案 3 :(得分:2)

更新了代码,并在click上添加了options事件

https://stackblitz.com/edit/angular-material-w89kwc?embed=1&file=app/app.component.ts

添加了一个功能

  getInnerText(innerText){
    console.log(innerText)
  }

在视图中添加了点击事件

<mat-option *ngFor="let familyRelation of familyRelationArray;" [value]="familyRelation.family_relation_id" (click)="getInnerText(familyRelation.family_relation_type)">
    {{familyRelation.family_relation_type}}
</mat-option>

答案 4 :(得分:1)

虽然有点晚了,但是答案启发了我一下,这里有个主意:

export interface IFamilyGroup{
    id: number;
    name: string;
    address: string;
}

familyGroup: IFamilyGroup[];

getSelectOption( family: IFamilyGroup ): void {
    console.log(family);
}

<mat-select (selectionChange)="getSelectOption( familyGroup[$event.value] )">
  <mat-option>none</mat-option>
  <mat-option
    *ngFor="let family of familyGroup; let i = index"
    value="{{i}}">
        {{ family.name }}
    </mat-option>
</mat-select>

此方法的缺点是您不能使用formControlName,因为mat-option使用index作为值,因此,如果要匹配formgroup,可以将其更改为:

// this is formgroup data model
export interface IFamilyGroup{
    id: number;
    name: string;
    address: string;
}

export interface IFormGroupDataForm{
    family: FormControl;
    whatever1?: FormControl;
    whatever2?: FormControl;
}


dataForm: FormGroup;
family = new FormControl();

familyGroup: IFamilyGroup[];

constructor(
    private formBuilder: FormBuilder
  ) { }

ngOnInit(): void {
    this.initFormGroup();
}

private initFormGroup() {
    dataForm = this.fromFormGroupModel({
      family: this.family
      // any you need...
    });
}

private fromFormGroupModel( model: IFormGroupDataForm ): FormGroup {
    return this.formBuilder.group(model);
}


getSelectOption( family: IFamilyGroup ): void {
    this.family.setValue(family); // set family data object be value
}



<div [formGroup]="dataForm">
    <mat-select (selectionChange)="getSelectOption( familyGroup[$event.value] )">
      <mat-option>none</mat-option>
      <mat-option
        *ngFor="let family of familyGroup; let i = index"
        value="{{i}}">
            {{ family.name }}
        </mat-option>
    </mat-select>

    //...
</div>

答案 5 :(得分:0)

您可以使用此方法。

<mat-select [(ngModel)]="job" #jobMatSelect placeholder="-Select Job-" class="form-control" required>
 <mat-option *ngFor="let item of Jobs" [value]="item.jobId" [disabled]="item.status == false" [ngClass]="{'col-red':item.status == false}"> ({{item.viewValue}})</mat-option>
 </mat-select>

Component.ts

 @ViewChild('jobMatSelect') private jobMatSelected: MatSelect;
 this.jobSelected = this.jobMatSelected.triggerValue;