Amit
Amit

Reputation: 1491

Setting Selected Value Mat-Select

My requirement is to show extraInfo in Mat Option. But when user selects any of the option I need not show the extra info once selected. To achieve this I am using .

But while trying to set value after form creation I am not able to do so.

My Code Below:

HTML---

<form [formGroup]="issueFieldsForm">

<mat-form-field appearance="fill" >
  <mat-label> Select</mat-label>
  <mat-select (selectionChange)="onchange($event)" formControlName="testDropDown">
    <mat-select-trigger >{{selected}}</mat-select-trigger>
    <mat-option *ngFor="let food of foods" [value]="food.value">
     
      {{food.viewValue}}
      <span>test</span>
    </mat-option>
  </mat-select>
</mat-form-field>

</form>

component.ts:

export class SelectOverviewExample implements OnInit{

  public selected: any;
  public issueFieldsForm: FormGroup;

  foods: Food[] = [
    {value: 'steak-0', viewValue: 'Steak'},
    {value: 'pizza-1', viewValue: 'Pizza'},
    {value: 'tacos-2', viewValue: 'Tacos'},
  ];

  public onchange(event:any){
    console.log(event);
    this.selected = this.foods.filter((obj)=> obj.value == event.value)[0].viewValue;
    console.log(this.selected)
  }
  constructor(private formBuilder: FormBuilder){

  }
  ngOnInit(): void {
      this.issueFieldsForm = new FormGroup<any | any>({testDropDown : new FormControl(null)})      
      this.issueFieldsForm.controls.testDropDown.setValue('tacos-2');
    }
}

One way is to filter the value and set by updating selected value. But I cannot do it. Because my dropdown is custom component itself. There I cannot pass the value.

Stackblitz for the issue: https://stackblitz.com/edit/angular-jwpwrm?file=src/app/select-overview-example.ts

Upvotes: 0

Views: 1932

Answers (2)

jitender
jitender

Reputation: 10429

Create a display function that will get the viewValue based on the selection inside your component something like

displayFunc(selectedVal:any){
    let food=this.foods.find(f=> f.value==selectedVal);
    return food?.viewValue;
  }

Then call this function inside mat select trigger

 <mat-select (selectionChange)="onchange($event)" formControlName="testDropDown" #select>
    <mat-select-trigger >{{displayFunc(select.value)}}</mat-select-trigger>

You can get the selected value using hash on mat select as well.

demo

Upvotes: 0

Pinaki
Pinaki

Reputation: 1030

Replace this line -

<mat-select-trigger >{{selected}}</mat-select-trigger>

with this -

<mat-option></mat-option>

Result -

ma-select-default-value

Upvotes: -1

Related Questions