Quick Contact


    Scalability and Validation Forms in Angular 8

    Form Validation

    Validation is an essential part of managing any set of forms. If we are checking for required fields or querying an external API for a username. Angular 8 provides a set of built-in validators moreover creating custom validators.

    Reactive forms

    In a reactive form, the cause of truth is the component class. In place of adding validators via attributes in the template, we can add validator function to control model in the component. After Angular call, these functions at the time value of the control changes.

    There are two validator functions:
    • Sync Validators
    • Async Validators
    Sync Validators:

    It is a type of service which controls instance and immediately returns either a set of validation errors or null. We can press these in as the second argument when we instantiate a Form Control.

    Async Validators:

    It is functions that take a control instance and return a promise or observable that later emits a set of validation error or null. We can pass these in as the third argument when we instantiate a Form Control.

    To update the hero form in a reactive form, we can use some of the same built-in validators.

    See the code:
    
    	ngOnInit(): void {
    	this.heroForm = new FormGroup({
    	'name': new FormControl(this.hero.name, [
    	Validators.required,
    	Validators.minLength(4),
    	forbiddenNameValidator(/bob/i) // 
    	<-- Here's how you pass in the custom validator.
    	]),
    	'alterEgo': new FormControl(this.hero.alterEgo),
    	'power': new FormControl(this.hero.power, Validators.required)
    	});
    	}
    	get name() { return this.heroForm.get('name'); 
    	get power() { return this.heroForm.get('power'); }
    	
    Template-driven validation:

    To add validation in a template-driven form, we add the same validation attributes as we will make with native HTML form validation. Angular uses directives to meet these attributes with validator functions in the framework.

    If the value of a form control changes, Angular runs validation and originate either a list of validation errors, which result in an invalid status or null, which occur in invalid condition.

    We can inspect the control’s state by exporting ngmodel to a local template variable.

    Example
    
    	< input id="name" name="name" class="form-control"
    	requiredminlength="4" appForbiddenName="bob"
    	[(ngModel)]="hero.name" #name="ngModel">
    	< div *ngIf="name.invalid&& (name.dirty || name.touched)"
    	class="alert alert-danger">
    	< div *ngIf="name.errors.required">
    	Name is required.
    	< /div>
    	< div *ngIf="name.errors.minlength">
    	Name must be atleast 4 characters long. 
    	< /div>
    	< div *ngIf="name.errors.forbiddenName">
    	Name cannot be Bob.
    	< /div>
    	< /div>
    	
    Testing of Forms in Angular 8

    Testing plays a significant role in complex applications, and a more uncomplicated testing strategy is useful when validating that our forms function correctly. Reactive forms and template-driven forms have many levels of perception to the UI to perform predictions placed on form control and form field changes. The following example demonstrates the process of testing forms with reactive forms with both reactive and template driven.

    Testing Reactive Forms

    Reactive forms provide an easy testing approach because they sustain synchronized access to the data and form models, and they can be tested without execution of the UI. In these tests, status and data are suspected and manipulated through the control without interacting with change detection cycle.

    The tests use the favorite color components mentioned earlier to verify the data flow from view to model and model to view to a reactive form.

    It verifies the data flow from view to the model.
    
    	it('should update the value of the input field', () => {
    	const input = fixture.nativeElement.querySelector('input');
    	const event = createNewEvent('input');
    	input.value = 'Red';
    	input.dispatchEvent(event);
    	expect(fixture.componentInstance.favoriteColorControl.value).toEqual('Red');
    	});
    	
    It verifies data flow from model to view
    
    	it('should update the value in the control', () => {
    	component.favoriteColorControl.setValue('Blue');
    	const input = fixture.nativeElement.querySelector('input');
    	expect(input.value).toBe('Blue');
    	});
    	
    Testing Template-driven forms

    Writing tests within template-driven forms requires a detailed knowledge of the change detection process and understanding, how directives run on each cycle to assure that elements are queried, tested, or changed at the correct time.

    These tests use the favorite color components specified earlier to verify the data flows from view to model and model to view for a template-driven form.

    It tests the data flow from view to model
    
    	it('should update the favorite color in the component', fakeAsync(() => {
    	const input = fixture.nativeElement.querySelector('input');
    	const event = createNewEvent('input');
    	input.value = 'Red';
    	input.dispatchEvent(event);
    	fixture.detectChanges();
    	expect(component.favoriteColor).toEqual('Red');
    	}));
    	
    It verifies the data flow from model to view
    
    	it('should update the favorite color on the input field', fakeAsync(() => {
    	component.favoriteColor = 'Blue';
    	fixture.detectChanges();
    	tick();
    	const input = fixture.nativeElement.querySelector('input');
    	expect(input.value).toBe('Blue');
    	}));
    	
    Scalability of Forms

    If forms are a central part of our application, scalability is essential. Being able to reuse the form model across a component is analytical.

    • Reactive forms maintain access to low-level APIs and synchronized access to the form model, creating productive large-scale structures easier.
    • Template-driven forms focus on the simple scenario, are not reusable, abstract away the low-level APIs, and provide asynchronous access to the form model.

    The abstraction with template-driven forms also in testing, where reactive testing forms requires less setup and no dependency on the change detection cycle updating and validating the form and data models during the trial.

    Copyright 1999- Ducat Creative, All rights reserved.