0

I want to fetch the option text of the option I selected with the option value also. What necessary changes do I need to make in my below code?

HTML

<mat-select (selectionChange)="changeQuestionValue($event.value)">
  <ng-container *ngFor="let q of QuestionCategory">
    <mat-option *ngIf="q.isActive" [value]="q.id">{{ q.questionCategoryName }}</mat-option>
  </ng-container>
</mat-select>

TS

changeQuestionValue(val) {
    return this.questionValue = val;
}

Here in TS am only receiving the q.id but I also want q.questionCategoryName.

Avishek
  • 524
  • 16
  • 38

3 Answers3

0

You just need to update the value property to [value]="q". But if you want to store the whole value in a form control you can use the compareWith function to return the object selected when by the option. Just define a function to compare the objects and the pass the whole object as a value in the mat-option.

e.g

  public compareWith(obj1: Question, obj2: Question) {
    return obj1 && obj2 && obj1.id === obj2.id;
  }
<mat-select [compareWith]="compareWith" (selectionChange)="onChangeSelect($event.value)">
  <ng-container *ngFor="let q of questionCategories">
    <mat-option *ngIf="q.isActive" [value]="q">{{ q.questionCategoryName }}</mat-option>
  </ng-container>
</mat-select>

Here is a live example https://stackblitz.com/edit/en-stackoverflow-62688705

marianocodes
  • 794
  • 1
  • 10
  • 19
0

I think you should just replace [value]="q"

<mat-select (selectionChange)="changeQuestionValue($event.value)">
  <ng-container *ngFor="let q of QuestionCategory">
    <mat-option *ngIf="q.isActive" [value]="q">{{ q.questionCategoryName }}</mat-option>
  </ng-container>
</mat-select>
Rohit Tagadiya
  • 3,373
  • 1
  • 25
  • 25
0

You need to replace

[value]="q"

to

value="{{q}}"

surendra kumar
  • 1,686
  • 11
  • 15