Monday, September 28, 2020

Forms in Angular

Using forms for user input is the mainstay of any frontend application. Angular framework provides a very robust API for handling forms. In Angular there are two different approaches to handling user input through forms-

  • Template-driven forms
  • Reactive forms

Both of these approaches for handling forms in Angular provides the functionality to-

  1. Capture user inputs from the UI (View)
  2. Validating user input
  3. Creating a form model and data model
  4. Provide a way to track changes in the form and update model accordingly.

In this post we’ll go through the common building blocks used by both approaches, differences between the two approaches and other information to help you decide which type of form works best for your situation.


Classes used in Angular forms

Whether you create a reactive form or a template-driven form following base classes are used.

  • FormControl- Represents an individual form control and tracks its value and validation status.
  • FormGroup- Represents a collection of form controls as a group and tracks the values and status for that collection of form controls.
  • FormArray- Tracks the same values and status for an array of form controls.
  • ControlValueAccessor- Its an interface that acts as a bridge between Angular FormControl instances and native DOM elements.

Angular Template-driven forms

In template-driven forms most of the form related functionality is in the template. Template-driven forms rely on directives in the template to create and manipulate the underlying object model. They're easy to add to an app, but they don't scale as well as reactive forms. If you have very basic form requirements and logic that can be managed solely in the template, template-driven forms could be a good fit.

In template-driven forms, the form model is implicit. The NgModel directive creates and manages a FormControl instance for a given form element.

Here is an example template and component implementing a single control form using template-driven forms.

import { Component } from '@angular/core';

@Component({
  selector: 'app-emp',
  template: `
    Employee Name: <input type="text" [(ngModel)]="empName">
  `
})
export class EmployeeComponent {
  empName = '';
}

Angular Reactive forms

With reactive forms form model is defined directly in the component class so you have direct, explicit access to the underlying forms object model. Compared to template-driven forms, they are more robust: they're more scalable, reusable, and testable.

The [formControl] directive links the explicitly created FormControl instance to a specific form element in the view, using an internal value accessor. Here is an example template and component implementing a single control form using reactive form.

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-reactive-emp',
  template: `
    Employee Name: <input type="text" [formControl]="empName">
  `
})
export class FavoriteColorComponent {
  empName= new FormControl('');
}

Template-driven Vs Reactive forms in Angular

1. Setup of form model

In Angular reactive forms form model is explicit, created in component class.

In Angular template-driven forms form model is implicit, created by directives.

2. Data model

Data model is structured and immutable in Reactive forms. Each time a change is triggered on the data model, the FormControl instance returns a new data model rather than updating the existing data model.

It is unstructured and mutable in template-driven forms. Relies on two-way data binding to update the data model in the component as changes are made in the template.

3. Updates from the view to the model and from the model to the view are synchronous in reactive forms.

Updates are asynchronous in template-driven forms.

4. Form validation

Reactive forms define custom validators as functions.

Template-driven forms are tied to template directives, and must provide custom validator directives that wrap validation functions.

5. Scalability

Reactive forms are more scalable than template-driven forms. They provide direct access to the underlying form API and synchronous access to the form data model, making creating large-scale forms easier.

Template-driven forms focus on simple scenarios and are not as reusable. They abstract away the underlying form API, and provide only asynchronous access to the form data model.

6. Data flow

In reactive forms each form element in the view is directly linked to the form model (a FormControl instance).

In template-driven forms, each form element is linked to a directive that manages the form model internally.

Reference: https://angular.io/guide/forms-overview

That's all for this topic Forms in Angular. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Location Strategies in Angular Routing
  2. Angular Cross Component Communication Using Subject Observable
  3. Nested Route (Child Route) in Angular
  4. Angular Custom Two-Way Data Binding
  5. Angular Class Binding With Examples

You may also like-

  1. Angular First App - Hello world Example
  2. Angular Disable Button Example
  3. Angular Application Bootstrap Process
  4. Angular ngClass Directive With Examples
  5. How to Remove Duplicate Elements From an ArrayList in Java
  6. break Statement in Java
  7. Python String isdigit() Method
  8. Spring MVC Redirect Example

Wednesday, September 23, 2020

Angular Cross Component Communication Using Subject Observable

In this post we’ll see how to use Subject observable for cross component communication in Angular.


Subject in RxJS Library

Subject is a type of Observable using which you can multicast values to many Observers, which makes it different from a plain Observables which are unicast (each subscribed Observer owns an independent execution of the Observable).

Thursday, September 17, 2020

What is Client Side Routing in Angular

While working with any modern JS frameworks like Angular, React, Vue you would have definitely come across two terms Single Page Application (SPA) and client side routing. In this post we’ll see what is client side routing using Angular as example framework.

Client side routing

In a traditional web application every request for displaying a page goes to the server and results in a full page load. Whereas in a Single page application each request doesn’t go to the server. Our web server gives the single page, any further rendering is done locally by the Java script. So, in a SPA you will get a single page and part of the page is updated dynamically for further requests.

Tuesday, September 15, 2020

Location Strategies in Angular Routing

In Angular routing we have two location strategies that we can use to implement client side routing.

  1. PathLocationStrategy
  2. HashLocationStrategy

In this post we’ll see what is location strategy, which routing strategy to chose for your SPA and what are the differences between the HashLocationStrategy and PathLocationStrategy.

Friday, September 11, 2020

How to Create a Custom Observable in Angular

In this post we’ll see how to create a custom Observable in Angular. Observables are based on Observer design pattern in which an object, called the subject, maintains a list of observers and notifies them automatically of state changes. Some thing like this-

public interface Subject {
	public void register(Observer obj);
	public void unregister(Observer obj);
	
	public void notifyObservers();
}