Reputation: 812
I create one user registration form and want submit this form, but I stuck here, my validation it's not work in submit form, also show my code,
This is Form submitting with validation, it's basic validation,
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);
}
}
Error
$ 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.
Upvotes: 0
Views: 1310
Reputation: 555
change this :
<div *ngIf = "login.controls.firstname.errors">First name Required</div>
Upvotes: 1
Reputation: 14002
as the error says the firstname.errors
can be null
and break the application, you need to include the ?
(called the safe navigation operator) like this:
<div *ngIf = "firstname.errors?.required">First name Required</div>
Upvotes: 3