Home > Software engineering >  Setting Selected Value Mat-Select
Setting Selected Value Mat-Select

Time:09-16

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: ma-select-default-value

  • Related