Angular模板驱动验证失效求助:FirstName为空提示不显示
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:
- Add the
requiredattribute to your firstName input. This tells Angular to apply the built-in required validator. - (Optional but cleaner) Use
firstName.invalidinstead of!firstName.validfor 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

