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

如何正确配置Angular mat-select?能否不在ngInit外声明jobTypes?

解决Angular mat-select表单提交无法获取值的问题

当然可以不用在ngOnInit外部单独声明jobTypes控件,你之前的问题核心是模板绑定的控件和FormGroup内的控件不是同一个实例,导致提交时无法同步值。以下是正确的实现方式:

正确写法(无需单独声明控件)

组件类代码

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
  // 仅声明表单组,无需单独定义jobTypes控件
  jobForm!: FormGroup;

  ngOnInit(): void {
    // 在FormGroup内部直接创建jobTypes控件
    this.jobForm = new FormGroup({
      jobTypes: new FormControl('')
    });
  }

  onSubmit(): void {
    // 从表单组中直接获取选中值
    console.log(this.jobForm.value.jobTypes);
  }
}

模板HTML代码

<form [formGroup]="jobForm" (ngSubmit)="onSubmit()">
  <mat-form-field>
    <mat-label>职位类型</mat-label>
    <mat-select formControlName="jobTypes">
      <mat-option value="fulltime">全职</mat-option>
      <mat-option value="parttime">兼职</mat-option>
      <mat-option value="contract">合同工</mat-option>
    </mat-select>
  </mat-form-field>
  <button type="submit">提交</button>
</form>

简化写法(使用FormBuilder)

如果觉得手动创建FormControl繁琐,可以用Angular的FormBuilder来简化代码,效果完全一致:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
  jobForm!: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.jobForm = this.fb.group({
      jobTypes: [''] // 括号内为控件初始值
    });
  }

  onSubmit(): void {
    console.log(this.jobForm.value.jobTypes);
  }
}

原理说明

之前你在外部声明jobTypes = new FormControl(''),又在FormGroup里重新创建new FormControl(''),这是两个完全独立的控件实例。模板绑定的是外部的那个,而表单提交时读取的是FormGroup内部的控件值,自然拿不到选中内容。

现在的写法是让模板通过formControlName直接绑定到FormGroup内部的控件,两者是同一个实例,提交时就能正常同步选中值,同时也不需要在外部单独声明控件变量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 10:30:52