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

Angular模板驱动验证失效求助:FirstName为空提示不显示

Fixing Template-Driven Validation for Your Angular Form

Hey there! Let's get that validation working for your firstName field. The root issue here is that your input doesn't have a required validation rule—Angular has no way to know this field should be mandatory, so firstName.valid remains true even when it's empty, which is why your error message never shows up.

Here's what you need to do:

  1. Add the required attribute to your firstName input. This tells Angular to apply the built-in required validator.
  2. (Optional but cleaner) Use firstName.invalid instead of !firstName.valid for more readable logic.

Modified Code:

<form>
  <div class="form-group">
    <label for="firstName"> First name </label>
    <input 
      ngModel 
      name="firstName" 
      id="firstName" 
      #firstName="ngModel" 
      (change)="log(firstName)" 
      type="text" 
      class="form-control"
      required <!-- Add this line -->
    >
    <div class="alert alert-danger" *ngIf="firstName.touched && firstName.invalid">
      first name mandatory
    </div>
  </div>
  <div class="form-group">
    <label for="comment"> Comment </label>
    <textarea 
      ngModel 
      name="comment" 
      id='comment' 
      cols="30" 
      rows="10" 
      class="form-control"
    ></textarea>
  </div>
  <button class="btn btn-primary">submit</button>
</form>

Quick Check:

Make sure your AppModule (or the module where this component lives) has imported FormsModule from @angular/forms—without this, template-driven forms and ngModel won't work at all. Your module should look something like this:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // Import this

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule // Add this to imports array
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now when you touch the firstName input and leave it empty, the Bootstrap danger alert should show up as expected!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:44:11