Search code examples
angularangular-materialangular-reactive-formsangular7

Angular 7 and angular material how to get the selected option text of mat-select instead of its value


I need to get the selected text of material drop down list <mat-select> instead of its value:

<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>

And here is how I am trying to do:

@ViewChild('familyRelation') familyRel: ElementRef;

And on change selection of the drop list:

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

I had the following error:

ERROR TypeError: Cannot read property 'innerText' of undefined at

And when I remove innerText, the consoled value is:

undefined

What I need as you can see in the stackblitz, if I chosed Parent, I want to get Parent into a variable and not 1 which is its id.

Please note that element, i and hh in (selectionChange)=onChange(element,...) are used later in the function, so forget about it now.


Solution

  • Updated the code, and added click event on the options

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

    Added one function

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

    Added click event in view

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