You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular下拉列表无法读取值问题求助

问题分析与修复

核心问题:FormControl取值方式错误

你的RR是单个FormControl实例,并非FormGroup,因此不能用this.RR.get('reasons').value来取值,直接访问this.RR.value即可获取选中的下拉选项值。

次要优化:空选项的value设置

默认的--选项未设置[value],选中它时会导致FormControl的值为undefined,建议显式设置[value]="null",确保表单验证逻辑正常触发。


修改后的Component.ts代码

retrievalReason: Reasons;
RR = new FormControl('', Validators.required);

reasons: Reasons[] = [
  {reason: 'Cycle Count'},
  {reason: 'Purge Request'},
  {reason: 'Picking'},
];

done() {
  this.dialogRef.close({
    carrier: this.carrier,
    destination: this.selection.selected[0].dstId,
    // 直接获取FormControl的value
    retrievalReason: this.RR.value,
  });
}

修改后的Component.html代码(优化空选项)

<mat-form-field appearance="fill">
  <mat-label>Retrieval Reason</mat-label>
  <mat-select [formControl]="RR" required>
    <!-- 显式设置空选项的value -->
    <mat-option [value]="null">--</mat-option>
    <mat-option *ngFor="let reason of reasons" [value]="reason">
      {{reason.reason}}
    </mat-option>
  </mat-select>
  <mat-error *ngIf="RR.hasError('required')">Please choose a reason</mat-error>
</mat-form-field>

<button
  mat-raised-button
  (click)="done()"
  color="primary"
  [disabled]="selection.selected.length === 0 || RR.hasError('required')"
>
  Retrieve
</button>

额外说明

如果只需获取选中选项的reason字符串(如"Cycle Count"),而非整个对象,可将mat-option的[value]改为reason.reason,此时this.RR.value会直接返回字符串:

<mat-option *ngFor="let reason of reasons" [value]="reason.reason">
  {{reason.reason}}
</mat-option>

内容的提问来源于stack exchange,提问作者Mathew Dodson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 01:25:14