I can't select options of mat-select and can't make the selected option appear in console

373 Views Asked by At

I have the following problem: I have a drop down list with 2 items. I need the first one to appear by default and that when selecting either of the two its value is shown in the console and saved in a variable. I have the following code:

HTML

<td>
  <mat-select name="tipoCdp" (change)="onChangeCdp($event.value)" [(ngModel)]="tipoCdpValue">
    <ng-container *ngFor="let gas of tipoc">
      <mat-option [value]="gas.viewValue">
        {{gas.viewValue}}
      </mat-option>
    </ng-container>                                
  </mat-select>
</td>

TS

interface tipoCdp {
  value: string;
  viewValue: string;
}

@Component({
  selector: '...',
  templateUrl: '...',
  styleUrls: ['...']
})

export class showValue implements OnInit {

constructor (...) { ... }

tipoc: tipoCdp[] = [
    {value: 'gasto-0', viewValue: 'GASTO'},
    {value: 'modificacion-1', viewValue: 'MODIFICACIÓN ANEXO DECRETO'}
  ];

  //selected = this.tipoc[0].value; --> /* With this line I was selecting the firts element but the value was burned */

  onChangeCdp(event) {
    console.log(event);
    this.tipoc = event;
  }

}

When I run the program in "event" the selected item appears, but then the following error appears on the console:

"Error trying to diff 'GASTO'. Only arrays and iterables are allowed"

Thanks for your help!

1

There are 1 best solutions below

0
On

In your template you are setting the value of the option from the gas.viewValue which will not match. If you replace it with gas.value and adjust your component class like this working example:

<mat-select name="tipoCdp" [(ngModel)]="tipoCdpValue">
  <ng-container *ngFor="let gas of tipoc">
    <mat-option [value]="gas.value">
      {{gas.viewValue}}
    </mat-option>
  </ng-container>                                
</mat-select>

Your component class:

  ...

  tipoCdpValue: any;

  constructor() {
    this.tipoCdpValue = this.tipoc[0].value; // to get the first option selected
  }
...

If you want to listen on the selection changes you could add (ngModelChange)="onChange($event)" on your mat-select element