<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>formbuilder angular &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/formbuilder-angular/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>ASP.NET Hosting &#124; Reviews &#124; Tips &#38; Tutorial</description>
	<lastBuildDate>Thu, 25 Aug 2022 04:35:56 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://topreviewhostingasp.net/wp-content/uploads/2017/01/cropped-trhaico-32x32.png</url>
	<title>formbuilder angular &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Angular Tips &#8211; Build Clean Forms Using Reactive Forms</title>
		<link>https://topreviewhostingasp.net/angular-tips-build-clean-forms-using-reactive-forms/</link>
					<comments>https://topreviewhostingasp.net/angular-tips-build-clean-forms-using-reactive-forms/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Thu, 25 Aug 2022 04:21:47 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[angular]]></category>
		<category><![CDATA[angular tips]]></category>
		<category><![CDATA[angular tutorial]]></category>
		<category><![CDATA[clean forms angular]]></category>
		<category><![CDATA[formbuilder angular]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3142</guid>

					<description><![CDATA[Reactive forms in Angular enable you to build clean forms without using too many directives. This is critical because: JavaScript frameworks typically caution against using clustered templates Form logic now lies in the component class Essentially, Angular reactive forms give developers more control because every decision related to inputs and controls must be intentional and explicit. To [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Reactive forms in Angular enable you to build clean forms without using too many directives. This is critical because:</p>



<ul>
<li>JavaScript frameworks typically caution against using clustered templates</li>
<li>Form logic now lies in the component class</li>
</ul>



<p>Essentially, <a href="https://angular.io/guide/reactive-forms" target="_blank" rel="noreferrer noopener">Angular reactive forms</a> give developers more control because every decision related to inputs and controls must be intentional and explicit.</p>



<p>To ensure the quality of your data, it’s always a good practice to <a href="https://angular.io/guide/form-validation" target="_blank" rel="noreferrer noopener">validate reactive form input</a> for accuracy and completeness. In this tutorial, we’ll show you how to validate reactive forms in Angular using <code>FormBuilder</code>.</p>



<p>To follow along, make sure you have the latest versions of <a href="https://nodejs.org/en/" target="_blank" rel="noreferrer noopener">Node.js (15.5.0)</a> and <a href="https://github.com/angular/angular" target="_blank" rel="noreferrer noopener">Angular (11.0.5)</a> installed, along with the <a href="https://github.com/angular/angular-cli/releases" target="_blank" rel="noreferrer noopener">Angular CLI (11.0.5)</a>. You can download the starter project on <a href="https://github.com/viclotana/ng-group" target="_blank" rel="noreferrer noopener">GitHub</a>.</p>



<h2 class="wp-block-heading" id="formcontrolsandformgroupsinangular">Form controls and form groups in Angular</h2>



<p>Form controls are classes that can hold both the data values and the validation information of any form element, which means every form input you have in a reactive form should be bound by a form control. These are the basic units that make up reactive forms.</p>



<p><code>FormControl</code> is a class in Angular that tracks the value and validation status of an individual form control. One of the three essential building blocks in Angular forms — along with <code>FormGroup</code> and <code>FormArray</code> — <code>FormControl</code> extends the <code>AbstractControl</code> class, which enables it to access the value, validation status, user interactions, and events.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://www.asphostportal.com" target="_blank" rel="noopener"><img fetchpriority="high" decoding="async" width="300" height="271" class="wp-image-2584 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2018/11/ahp-banner-aspnet-01-50x45.png 50w" sizes="(max-width: 300px) 100vw, 300px" /></a></figure>
</div>



<p>Form groups are constructs that basically wrap a collection of form controls. Just as the control gives you access to the state of an element, the group gives the same access, but to the state of the wrapped controls. Every single form control in the form group is identified by name when initializing.</p>



<p><code>FormGroup</code> is used with <code>FormControl</code> to track the value and validate the state of form control. In practice,  <code>FormGroup</code> aggregates the values of each child <code>FormControl</code> into a single object, using each control name as the key. It calculates its status by reducing the status values of its children so that if one control in a group is invalid, the entire group is rendered invalid.</p>



<h2 class="wp-block-heading" id="whatisformvalidationinangular">What is form validation in Angular?</h2>



<p>Form validation in Angular enables you to verify that the input is accurate and complete. You can validate user input from the UI and display helpful validation messages in both template-driven and reactive forms.</p>



<p>When validating reactive forms in Angular, validator functions are added directly to the form control model in the component class. Angular calls these functions whenever the value of the control changes.</p>



<p>Validator functions can be either synchronous or asynchronous:</p>



<ul>
<li>Synchronous validators take a control instance and return either a set of errors or null. When you create a <code>FormControl</code>, you can pass sync functions in as the second argument.</li>
<li>Asynchronous validators take a control instance and return a Promise or an Observable that later issues either a set of errors or null. You can pass async functions in as the third argument when you instantiate a <code>FormControl</code>.</li>
</ul>



<p>Depending on the unique needs and goals of your project, you may choose to either <a href="https://angular.io/guide/form-validation#validating-input-in-reactive-forms" target="_blank" rel="noreferrer noopener">write custom validator functions</a> or use any of Angular’s <a href="https://angular.io/api/forms/Validators" target="_blank" rel="noreferrer noopener">built-in validators</a>.</p>



<p>Without further ado, let’s get started building reactive forms.</p>



<h2 class="wp-block-heading" id="whatisformbuilder">What is <code>FormBuilder</code>?</h2>



<p>Setting up form controls, especially for very long forms, can quickly become both monotonous and stressful. <code>FormBuilder</code> in Angular helps you streamline the process of building complex forms while avoiding repetition.</p>



<p>Put simply, <code>FormBuilder</code> provides syntactic sugar that eases the burden of creating instances of <code>FormControl</code>, <code>FormGroup</code>, or <code>FormArray</code> and reduces the amount of boilerplate required to build complex forms.</p>



<h2 class="wp-block-heading" id="howtouseformbuilder">How to use <code>FormBuilder</code></h2>



<p>The example below shows how to build a reactive form in Angular using <code>FormBuilder</code>.</p>



<p>You should have downloaded and opened the <a href="https://github.com/viclotana/ng-group">starter project</a> in VS Code. If you open the <code>employee.component.ts</code>, file it should look like this:</p>



<pre class="wp-block-code"><code>import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms'
@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
  bioSection = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    age: new FormControl(''),
    stackDetails: new FormGroup({
      stack: new FormControl(''),
      experience: new FormControl('')
    }),
    address: new FormGroup({
        country: new FormControl(''),
        city: new FormControl('')
    })
  });
constructor() { }
ngOnInit() {
  }
  callingFunction() {
    console.log(this.bioSection.value);
   }
}</code></pre>



<p>You can see that every single form control — and even the form group that partitions it — is spelled out, so over time, you end up repeating yourself. <code>FormBuilder</code> helps solve this efficiency problem.</p>



<h3 class="wp-block-heading" id="registeringformbuilder">Registering <code>FormBuilder</code></h3>



<p>To use <code>FormBuilder</code>, you must first register it. To register <code>FormBuilder</code> in a component, import it from Angular forms:</p>



<pre class="wp-block-code"><code>import { FormBuilder } from ‘@angular/forms’;</code></pre>



<p>The next step is to inject the form builder service, which is an injectable provider that comes with the reactive forms module. You can then use the form builder after injecting it. Navigate to the <code>employee.component.ts</code> file and copy in the code block below.</p>



<pre class="wp-block-code"><code>import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms'
@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
  bioSection = this.fb.group({
    firstName: [''],
    lastName: [''],
    age: [''],
    stackDetails: this.fb.group({
      stack: [''],
      experience: ['']
    }),
    address: this.fb.group({
        country: [''],
        city: ['']
    })
  });
constructor(private fb: FormBuilder) { }
ngOnInit() {
  }
  callingFunction() {
    console.log(this.bioSection.value);
   }
}</code></pre>



<p>This does exactly the same thing as the previous code block you saw at the start, but you can see there is a lot less code and more structure — and, thus, optimal usage of resources. Form builders not only help to make your reactive forms’ code efficient, but they are also important for form validation.</p>



<h2 class="wp-block-heading" id="howtovalidateformsinangular">How to validate forms in Angular</h2>



<p>Using reactive forms in Angular, you can validate your forms inside the form builders.</p>



<p>Run your application in development with the command:</p>



<pre class="wp-block-code"><code>ng serve</code></pre>



<p>You will discover that the form submits even when you do not input values into the text boxes. This can easily be checked with form validators in reactive forms. The first thing to do, as with all elements of reactive forms, is to import it from Angular forms.</p>



<pre class="wp-block-code"><code>import { Validators } from '@angular/forms';</code></pre>



<p>You can now play around with the validators by specifying the form controls that must be filled in order for the submit button to be active. Copy the code block below into the <code>employee.component.ts</code> file:</p>



<p>The last thing to do is to make sure the submit button’s active settings are set accordingly. Navigate to the <code>employee.component.html</code> file and make sure the submit statement looks like this:</p>



<pre class="wp-block-code"><code>&lt;button type=”submit” [disabled]=”!bioSection.valid”&gt;Submit Application&lt;/button&gt;</code></pre>



<p>If you run your application now, you will see that if you do not set an input for first name, you cannot submit the form — isn’t that cool?</p>



<h3 class="wp-block-heading" id="displayinginputvaluesandstatus">Displaying input values and status</h3>



<p>Let’s say you want to use the value and status properties to display, in real-time, the input values of your reactive form and whether it can be submitted or not.</p>



<p>The reactive forms API lets you use the value and status properties on your form group or form controls in the template section. Open your <code>employee.component.html</code> file and copy in the code block below:</p>



<pre class="wp-block-code"><code>&lt;form [formGroup]="bioSection" (ngSubmit)="callingFunction()"&gt;
    &lt;h3&gt;Bio Details
&lt;/h3&gt;

  &lt;label&gt;
    First Name:
    &lt;input type="text" formControlName="firstName"&gt;
  &lt;/label&gt; &lt;br&gt;
&lt;label&gt;
    Last Name:
    &lt;input type="text" formControlName="lastName"&gt;
  &lt;/label&gt; &lt;br&gt;
&lt;label&gt;
    Age:
    &lt;input type="text" formControlName="age"&gt;
  &lt;/label&gt;
&lt;div formGroupName="stackDetails"&gt;
    &lt;h3&gt;Stack Details&lt;/h3&gt;

    &lt;label&gt;
      Stack:
      &lt;input type="text" formControlName="stack"&gt;
    &lt;/label&gt; &lt;br&gt;

    &lt;label&gt;
      Experience:
      &lt;input type="text" formControlName="experience"&gt;
    &lt;/label&gt;
  &lt;/div&gt;
&lt;div formGroupName="address"&gt;
    &lt;h3&gt;Address&lt;/h3&gt;

    &lt;label&gt;
      Country:
      &lt;input type="text" formControlName="country"&gt;
    &lt;/label&gt; &lt;br&gt;

    &lt;label&gt;
      City:
      &lt;input type="text" formControlName="city"&gt;
    &lt;/label&gt;
  &lt;/div&gt;
&lt;button type="submit" [disabled]="!bioSection.valid"&gt;Submit Application&lt;/button&gt;
  &lt;p&gt;
    Real-time data: {{ bioSection.value | json }}
  &lt;/p&gt;
  &lt;p&gt;
    Your form status is : {{ bioSection.status }}
  &lt;/p&gt;
&lt;/form&gt;</code></pre>



<p>This displays both the value and the status for submission for you in the interface as you use the form. The complete code to this tutorial can be <a href="https://github.com/viclotana/ng-group">found here on GitHub</a>.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>This article gives an overview of the form builder and how it is a great efficiency enabler for form controls and form groups. It also shows how important it can be for handling form validation easily with reactive forms.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/angular-tips-build-clean-forms-using-reactive-forms/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
