Attempting to validate a template-driven form in Angular without two-way data binding has proved to be challenging. I have successfully implemented validation using [(ngModel)]
, but running into an error when trying to validate the form without the MODEL present.
The error message I am encountering is Cannot read property 'invalid' of undefined.
Below is my HTML code:
<div class="jumbotron">
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<h3>Angular 6 Template-Driven Form Validation</h3>
<form name="form" (ngSubmit)="onSubmit(f.value)" #f="ngForm" novalidate>
<div class="form-group">
<label for="username">Username:</label>
<input type="text"
class="form-control"
name="username"
#userName
required
minlength="8"/>
<div *ngIf="f.form.controls.username.invalid && f.form.controls.username.touched" class="invalid-feedback">
<div *ngIf="f.form.controls.username.errors.required" class="alert alert-danger">Username is required</div>
<div *ngIf="f.form.controls.username.minlength" class="alert alert-danger">length should b 8 character</div>
</div>
</div>
<button class="btn btn-primary" >Register</button>
</form>
</div>
</div>
</div>
</div>
Additionally, the form is failing to send data to the component when the submit button is clicked.
Here is the TypeScript file for the component:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-template-driven-form',
templateUrl: './template-driven-form.component.html',
styleUrls: ['./template-driven-form.component.css']
})
export class TemplateDrivenFormComponent {
// model: any = {};
onSubmit(f) {
// alert('SUCCESS!! :-)\n\n' + f);
console.log(f);
}
}