我创建了一个用户注册表单并想提交此表单,但我卡在这里,我的验证在提交表单中不起作用,还显示我的代码,
这是带验证的表单提交,它是基本验证,
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>
形成compoenet.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.