From:
A form contains various input components like text, option, select option and pickers. This input component behavior is manipulated into Form. A form is operated to two-way data binding, validation, event binding and error handling while submitting the form or inline validate.
Template Driven form:
A Template Driven Form creates a set angular structure based directives.
Example:
I create execute the following angular-CLI code:
ng g component tempdrivenfrm
Now, the template driven component is created successfully. We write a logic for the corresponding files.
HTML:
<div class="form-group">
<div class="form-group">
<label>User Name</label>
<input type="text" #myNameRef="ngModel" required minlength="5" class="form-control" name="name" ngModel>
<div *ngIf=" myNameRef.errors && (myNameRef.dirty || myNameRef.touched)">
<div [hidden]=" !myNameRef.errors.required ">
Please enter the name
</div>
<div [hidden]=" !myNameRef.errors.minlength ">
Please enter minum 5 character
</div>
</div>
</div>
<div class="form-group">
<label>User email</label>
<input type="text" #myEmailRef="ngModel" required class="form-control" name="email" ngModel >
</div>
<div [hidden]=" myEmailRef.valid || myEmailRef.pristine " class="alert alert-danger">
Please enter the email
</div>
<div class="form-group">
<label>User phone</label>
<input type="phone" class="form-control" name="phone" ngModel>
</div>
<div ngModelGroup="address">
<div class="form-group">
<label>User street</label>
<input type="text" class="form-control" name="street" ngModel>
</div>
<div class="form-group">
<label>User city</label>
<input type="text" class="form-control" name="city" ngModel>
</div>
</div>
<button type="submit" class="btn btn-primary btn-lg"> Submit </button>
</div>
</form>
CSS:
input.ng-invalid {
border-left: 5px solid red;
}
input.ng-valid {
border-left: 5px solid green;
}
.error-message {
color: red;
padding-left: 10px;
}
Typescript:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-tempdrivenfrm',
templateUrl: './tempdrivenfrm.component.html',
styleUrls: ['./tempdrivenfrm.component.css']
})
export class TempdrivenfrmComponent implements OnInit {
myName: string;
constructor() { }
ngOnInit() {
this.myName = "";
}
userFormSubmit(frmValidation: any){
console.log(frmValidation.value);
}
}
Result:
Comments
Post a Comment