0

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 ?

Sami-L
  • 5,553
  • 18
  • 59
  • 87

2 Answers2

1

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.

Anto Antony
  • 842
  • 6
  • 12
  • can you please answer this: https://stackoverflow.com/questions/60465057/angular-rxjs-getting-subscriber-instead-of-the-required-value – Sami-L Feb 29 '20 at 18:57
0

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]
    });
}
klebers
  • 41
  • 3