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

使用Object.keys搭配Switch始终返回默认值的Angular表单问题

问题分析与解决

错误原因

你代码里的for(const key in Object.keys(errors))是问题核心:

  • Object.keys(errors)返回的是错误键名组成的数组,比如你测试时的['minlength']
  • for...in循环遍历数组时,拿到的是数组的索引(字符串类型的数字,比如这里的'0'),而不是数组里的错误键名'minlength'
  • 所以switch(key)里的case 'minlength'永远匹配不上,直接触发default返回'hi'

修正方案

有两种常用的修正方式:

方式一:用for...of遍历错误键名数组

for...of会直接遍历数组的元素,拿到正确的错误键名:

public getFieldError(form: FormGroup, field:string):string | null{
  if(!form) return null;

  const control = form.controls[field];
  if (!control || !control.errors) return null;
  
  const errorKeys = Object.keys(control.errors);
  for(const key of errorKeys) {
    switch(key){
      case 'required':
        return 'required error';
      case 'minlength':
        return 'minlength error';
      default:
        return 'hi'; 
    }
  }

  return null;
}

方式二:直接取第一个错误键(更简洁)

表单字段通常同一时间只会触发一个校验错误,所以可以直接取数组的第一个元素,省略循环:

public getFieldError(form: FormGroup, field:string):string | null{
  if(!form) return null;

  const control = form.controls[field];
  if (!control || !control.errors) return null;
  
  const firstErrorKey = Object.keys(control.errors)[0];
  switch(firstErrorKey){
    case 'required':
      return 'required error';
    case 'minlength':
      return 'minlength error';
    default:
      return 'hi'; 
  }
}

内容的提问来源于stack exchange,提问作者Bayes-T

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 22:12:32