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

Angular响应式表单报错及mat-select对象数组默认选中问题求助

问题解决:Angular响应式表单与mat-select对象类型选项的两个问题

1. 错误 control.registerOnChange is not a function 的修复

你将test声明为FormGroup,但mat-select的formControlName只能绑定到FormControl而非FormGroup。Angular尝试把表单组当作表单控件绑定到组件时,会因表单组缺少registerOnChange方法(表单控件专属方法)抛出该错误。

2. mat-select 默认选中对象类型选项的实现

当选项是对象类型时,不能拆分id和name单独初始化,需将表单控件的初始值设为对应完整对象,同时通过compareWith函数告诉Angular如何判断对象相等性。

修正后的完整代码

组件TS代码

import { Component } from '@angular/core';
import { FormBuilder, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  tags: { id: number; name: string }[] = [
    { id: 1, name: 'tag1' },
    { id: 2, name: 'tag2' },
    { id: 3, name: 'Jack' },
  ];

  form = this.fb.group({
    loadSettings: this.fb.group({
      // 将test从FormGroup改为FormControl,初始值设为匹配的tag对象
      test: new FormControl(this.tags.find(tag => tag.id === 2), Validators.required),
    }),
  });

  constructor(private fb: FormBuilder) {}

  // 通过id判断两个选项对象是否相等
  compareFn(obj1: { id: number }, obj2: { id: number }): boolean {
    return obj1 && obj2 ? obj1.id === obj2.id : obj1 === obj2;
  }
}

模板代码

<form [formGroup]="form">
  <div formGroupName="loadSettings">
    <div class="au-mat-column-lg-px" style="padding-top: 76px;">
      <mat-form-field class="full-width">
        <mat-select [compareWith]="compareFn" formControlName="test">
          <mat-option *ngFor="let option of tags" [value]="option">
            <span>{{ option.name }}</span>
          </mat-option>
        </mat-select>
      </mat-form-field>
    </div>
  </div>
</form>

关键要点总结

  • 确保mat-select绑定的是FormControl而非FormGroup
  • 初始值需设置为选项数组中的完整对象(通过find方法匹配获取)
  • 实现compareFn函数,基于对象的唯一标识(如id)进行相等性判断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 20:42:11