0

我有以下问题:我有一个包含 2 个项目的下拉列表。我需要默认情况下出现第一个,并且在选择两个值中的任何一个时,将显示在控制台中并保存在变量中。我有以下代码:

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;
  }

}

当我在“事件”中运行程序时,会出现所选项目,但随后控制台上会出现以下错误:

“尝试区分 'GASTO' 时出错。只允许使用数组和可迭代对象”

谢谢你的帮助!

4

1 回答 1

0

在您的模板中,您正在设置不匹配的 gas.viewValue 选项的值。如果你用 gas.value 替换它并像这个工作示例一样调整你的组件类:

<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>

您的组件类:

  ...

  tipoCdpValue: any;

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

如果您想收听选择更改,您可以(ngModelChange)="onChange($event)"mat-select元素上添加

于 2021-12-06T09:37:27.217 回答