Sami-L
Sami-L

Reputation: 5705

Angular Material Select (mat-select) - How to set default value

A lot of questions are discussing the way to set a default value to show in a "Select" control, here I am exposing an Angular 8 template driven forms case, where I cannot get the default value showing in the mat-select when the button is clicked, even if console.log shows the correct value:

<mat-select [formControl]="itemControl" required [(value)]="itemValue">
    <mat-option>--</mat-option>
    <mat-option *ngFor="let item of items" [value]="item">{{item}}</mat-option>
</mat-select>

My component code part is as follows:

export class MyComponent {

  items: string[] = [''];
  itemControl = new FormControl('', [Validators.required]);
  itemValue: string = '';

  myButtonClick(): void {
        this.itemValue = this.getItems()[0];     <--- This returns the first element in a valid array
        console.log(this.itemValue);
      }
}

So what am I doing wrong ?

Upvotes: 0

Views: 728

Answers (2)

Anto Antony
Anto Antony

Reputation: 872

Since you are using form control, you should assign the default value to itemControl, for example

  this.itemControl.patchValue(this.getItems()[0])

You can assign it from the onInit lifecycle hook or from the api response. So the form control can update the value accordingly. mat-select directive don't support two way data binding for value property.

Upvotes: 1

klebers
klebers

Reputation: 41

Example:

html:

 <form [formGroup]="entregaSelecao">
       <mat-form-field class="form-input">
           <mat-label>Bairro</mat-label>
           <mat-select disableRipple formControlName="bairro">
              <mat-option  *ngFor="let item of bairros" [value]="item">{{item}}</mat-option>
           </mat-select>
       </mat-form-field>
   </form>

.ts:

public enderecoForm: FormGroup;

bairros: string[] = ['bairro 1', 'bairro 2', 'bairro 3'];
ngOnInit() {
    this.entregaSelecao = this.formBuilder.group({
          entregaSelecionado: ['', Validators.required]
    });
}

Upvotes: 0

Related Questions