Angular -> Can the text in an HTML Select be different than what the user selected from the drop down list?

I am working (in an Angular project) with a form where the user selects something from a HTML Select. from the example below, the "Cat" and "Dog" are optgroup(s) and the other things listed are option(s) attributes. Im wondering if it is possible to have the user select from the drop down, say the "Lion" option, and the text that populates the collapsed version of the drop down to read something like.. Cat: Lion.


  • Lion
  • Bobcat Dog
  • Wolf
  • Clifford

Is it possible to do this with just Angular (not jquery)



thanks to the help of shashank sharma’s comment i was able to figure it out. i used the example he gave and was able to get it to work by making the label a variable in the typescript and then setting that variable in the onCategorySelection function




onCategorySelection(event: MatOptionSelectionChange, groupName: string) {     if (event.isUserInput) {       this.selected = groupName +  ':' + event.source.viewValue;      ----->>>> this.animalKingdom = groupName +  ':' + event.source.viewValue;     }   } 
Add Comment
1 Answer(s)

Solution of this problem can’t be done with selectionChange event, we have to use onSelectionChange event of MatOption which gives us info of MatOptionGroup. for example

<mat-select>   <mat-optgroup *ngFor="let group of categoryGroups"                 [label]="">     <mat-option *ngFor="let category of group.options"                 [value]="category.value" (onSelectionChange)="onCategorySelection($event,">        {{category.viewValue}}     </mat-option>   </mat-optgroup>  </mat-select> 

and Typescript

onCategorySelection(event: MatOptionSelectionChange, groupName: string) {     if (event.isUserInput) {       this.groupName = groupName;      }   } 

I have create a working example for you here please accept / upvote answer if it works for you.

ps: remeber onSelectionChanged() is fired not only when an option is selected but also when it is deselected so if you are using met select with checkbox where we select and deselct onSelectionChanged() will fire both time( can be handeled with some checks).

Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.