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

Angular设置ng-required为true后页面加载时control.errors为null问题

问题原因

Angular 模板驱动表单默认不会在初始加载时主动执行校验,初始状态下表单控件为untouched(未触碰)、pristine(未修改)状态,因此不会生成错误对象,导致txtBox.errors为null。另外你代码中使用的ng-minlength、ng-required是AngularJS(1.x版本)的语法,如果你用的是Angular 2及以上版本,要改成带方括号的属性绑定写法,否则绑定的是固定字符串而非组件变量,校验规则本身就不会生效。


解决方案

1. 组件类逻辑修改

先通过@ViewChild获取表单控件实例,在组件初始化和输入框聚焦时手动触发校验:

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { NgModel } from '@angular/forms';

@Component({
  // 你的原有组件配置
})
export class YourComponent implements AfterViewInit {
  required = true;
  minlength = 3;
  value = '';
  @ViewChild('txtBox') txtBox!: NgModel;

  ngAfterViewInit(): void {
    // 组件加载完成后标记控件为已触碰,主动触发校验
    this.txtBox.control.markAsTouched();
    this.txtBox.control.updateValueAndValidity();
  }

  onFocus(event: Event): void {
    // 输入框聚焦时同样触发校验
    this.txtBox.control.markAsTouched();
    this.txtBox.control.updateValueAndValidity();
    // 保留你原有的其他聚焦逻辑
  }

  change(val: string): void {
    // 保留你原有的值变更逻辑
  }
}

2. 模板代码修改

修正校验属性的绑定写法,调整错误提示的显示条件:

<div *ngIf="required" class="inline required">
  *
</div>
<div class="input-container inline">
  <input type="text"
         #txtBox="ngModel"
         [(ngModel)]="value"
         (focus)="onFocus($event)"
         (ngModelChange)="change($event)"
         [minlength]="minlength"
         [required]="required">

  <!-- 控件已触碰且存在错误时展示提示 -->
  <div *ngIf="txtBox.touched && txtBox.errors">
    <div class="row alert alert-danger alert-div">
      <div *ngIf="txtBox.errors?.['required']">
        <span>
          Required field
        </span>
      </div>
      <div *ngIf="txtBox.errors?.['minlength']">
        <span>
          Min length error
        </span>
      </div>
    </div>
  </div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 07:45:01