问题描述
我创建了一个用户注册表并想提交此表单,但我卡在这里,我的验证在提交表单中不起作用,还显示了我的代码,
这是带有验证的表单提交,这是基本验证,
formcompoenet.componenet.html
<h3>Angular Form Component</h3>
<div class="container">
<h1>User Registration</h1>
<form #login="ngForm" (ngSubmit)="submit(login)">
<div class="form-group">
<label for="firstname">First Name</label><br/>
<input #firstname="ngModel" required minlength="2" maxlength="7" type="text" name="firstname" class="form-control" ngModel>
<div *ngIf = "firstname.invalid && (firstname.dirty || firstname.touched)" class="alert alert-danger">
ghhg
<div *ngIf = "firstname.errors.required">First name required</div>
<!-- <p *ngIf="firstname.errors.minlength">Firs name should be 2 char</p>
<p *ngIf="firstname.errors.maxlength">Firs name should be 12 char</p>-->
</div>
</div>
<pre></pre>
<div class="form-group">
<label for="lastname">Last Name</label><br/>
<input type="text" name="lastname" class="form-control" ngModel>
</div>
<pre></pre>
<div class="form-group">
<label for="email">Email ID</label><br/>
<input type="email" name="email" class="form-control" ngModel>
</div>
<pre></pre>
<div class="form-group">
<label for="password">Password</label><br/>
<input type="password" name="password" class="form-control" ngModel>
</div>
<pre></pre>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
formcompoenet.compoenent.ts
import { Component,OnInit } from '@angular/core';
@Component({
selector: 'app-formcomponenet',templateUrl: './formcomponenet.component.html',styleUrls: ['./formcomponenet.component.css']
})
export class FormcomponenetComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
submit(login:any) {
console.log("Fome Submit Successfull",login);
}
}
$ ng serve
√ browser application bundle generation complete.
Initial Chunk Files | Names | Size
vendor.js | vendor | 2.67 MB
polyfills.js | polyfills | 508.81 kB
styles.css,styles.js | styles | 381.00 kB
Error: src/app/formcomponenet/formcomponenet.component.html:11:48 - error TS2531: Object is possibly 'null'.
11 <div *ngIf = "firstname.errors.required">First name required</div>
~~~~~~~~
src/app/formcomponenet/formcomponenet.component.ts:5:18
5 templateUrl: './formcomponenet.component.html',~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component FormcomponenetComponent.
解决方法
由于错误指出 firstname.errors
可以是 null
并破坏应用程序,因此您需要像这样包含 ?
(称为安全导航运算符):
<div *ngIf = "firstname.errors?.required">First name Required</div>
,
改变这个:
<div *ngIf = "login.controls.firstname.errors">First name Required</div>