Template driven forms in Angular 2/4/6/7

  Angular

Developing forms requires design skills (which are out of scope for this page), as well as framework support for data binding, change tracking, validation, and error handling.

This page shows you how to build a simple form from scratch.

  1. Build an Angular form with a component and template.
  2. Use ngModel to create data bindings for reading and writing input-control values.
  3. Track state changes and the validity of form controls.
  4. Provide visual feedback using special CSS classes that track the state of the controls.
  5. Display validation errors to users and enable/disable form controls.
  6. Share information across HTML elements using template reference variables.
<form #form="ngForm">
<div class="form-group">
<label for="">First Name</label>
<input type="text" ngModel name="firstName" #firstName="ngModel" class="form-control mb-1" pattern="[a-z]{1,15}" minlength="3" required>
<div class="alert alert-danger" *ngIf="firstName.touched && !firstName.valid">
<div *ngIf="firstName.errors.required">* First Name is Required</div>
<div *ngIf="firstName.errors.minlength">* First Name minimum Length 3 required</div>
<div *ngIf = "firstName.errors.pattern">* FirstName Doesn't match Pattern - Pattern exm: premkarthi</div>
</div >
</div>
<div class="form-group">
<label for="">Comment</label>
<textarea ngModel name="comment" #comment="ngModel" id="" cols="30" rows="10" class="form-control mb-1" required></textarea>
<div class="alert alert-danger" *ngIf="comment.touched && !comment.valid">Comment is Required</div>
</div>
<div class="form-group">
<label for="">Subscribe our Mail Alerts </label>  
<input ngModel type="checkbox" name="checkbox" #checkbox="ngModel" class="form-checkbox" >
</div>

<button class="btn btn-info" [disabled]="!form.valid">Submit</button>

</form>
<br>
{{form.value | json}}

Spread the Code

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of