Reactive Forms (Angular)

We all know that Angular Application is a reactive system. We have two categories of form structures in Angular:

  1. Reactive Forms
  2. Template Driven Forms.

In template driven forms, the template directives are used. Whereas in reactive forms, we could build our own representation of the form in the components. Thus, we could always opt for Reactive Forms.

Let’s begin by knowing the terminologies of reactive forms.

  • formControl
  • formGroup
  • formArray
  • controlValueAccessor

In this blog, we are going to look through formControls and formGroup.

Before beginning, do not forget to import the module (ReactiveFormsModule) and import the classes (FormControl, FormGroup, FormBuilder, Validators)

Imagine you have a form with the following fields:

  1. Name
  2. Age
  3. School
  4. Class
  5. Rank

So here, each field will be having different data types (such as alphabets, numbers, etc). Thus, in reactive forms, validating the fields become very easy using the built-in properties. Also, it is very easy for us to group the individual forms and make the necessary changes.

Let’s start with formControl:
Each field is recognized using the formControls for validation. Thus, we will be setting formControl for each field. Also, default values to the fields can also be set up initially.

Illustration:
In .html file, add:

<input type="text" [formControl]="name">

In .ts file, add:

name = new FormControl('any default values');

And then we go for formGroup:
These individual form controls can be grouped together for better handling of validation stuff and named as formGroup.

Illustration:
Let the HTML file remain the same.
In .ts file, add:

formGroupVariable = new FormGroup({
name = new FormControl('Smith Katana'),
age: new FormControl(12),
});

Now using the formGroupVariable, several validations, customizations can be done using the inbuilt methods. Following are some of them:

Illustration:
In .ts file, add :

name = new FormControl('any default values', {validators: Validators.required, updateOn: 'blur'});

Here, in the second parameter, we could use the Validators Object for validations. Refer the following link for Validators API reference:
https://angular.io/api/forms/Validators

Also updateOn key will intimate the validators to validate only after every blur to avoid validations for every keystroke.

We could also add our own customized method validator by adding the method instead of Validator object as follows:

Illustration:

In .ts file, add :

name = new FormControl('any default values',validatorMethod);

function validatorMethod(name: FormControl) {
//custom validations
}

Note* This method will be called for every keystroke

If you want to have a validation like to submit the form if any of the validations have been passed and it is not necessary that all the fields should be passed. But how do we do that?

formGroupVariable.patchValue('name', { onlySelf: true });

….Simple right?

To enable or disable the form use,

formGroupVariable.enable() && formGroupVariable.disable()

And also to disable a particular form control initially we could use the disabled attribute,

Illustration:

name: new FormControl({ disabled: true, value: null })

Reference Links:

Asynchronous Generators

For all the asynchronous challenges that we face in our code, would be solved by either Async-Await or Promises. Here comes another powerful alternative module which we call them as Generators!!!

There is a mysterious secret behind these generators which I will reveal it in the final section of our blog.

Let’s define Generators in simple:

1. What are they?

They are generally function with a * notation

2. Why do we need them?

They are just like normal Javascript functions with the motive of pausing and resuming the required particular function executions, thereby achieving better execution control

Illustration:

   asyncGenerator(function* () {

     let promises=yield apiService.get("asyncDb/promises.json");

     console.log(promises);

     let callbacks=yield apiService.get("asyncDb/callbacks.json");

     console.log(callbacks);

     let asyncAwaits=yield apiService.get("asyncDb/asyncAwaits.json");

     console.log(asyncAwaits);

   })


   function asyncGenerator(generator){

     let a=generator();

     function handle(yieldObject){

       if(!yieldObject.done){

         yieldObject.value.then(function(data){

           return handle(a.next(data))

         })

       }

     }

     return handle(a.next());

   }

Illustration Explanation:

Here asyncGenerator is the generator. The keyword “yield” will pause the execution inside the function. Calling next() method each time will invoke the yield expressions separately one by one.

And most importantly the yield expression will return an object containing the keys value and done. The object is like,

{

value: {Promises…..} (the yielded return value will be here) 

done: false (states whether the generator execution have reached the end or not)

}

The above code looks almost the same as that of Async/await implementation. But what makes the difference is most important thing. Async/await returns a Promise, whereas Generators returns an object {value: X, done: Boolean}. Meanwhile yield returns a stream of values from the generators.

The error handling parts are very easier in generators when they are used along with RXJS filtering operators. Instead of using next() we could also use throw(error). Even we could force the generator to stop by using return() in place of next() methods.

When you are tired of using the next() method again and again, we could simplify it by using the setImmediate () method. This will make all the promises unwrap one by one and wait for them to resolve before calling the next iteration.

Example:  

“setImmediate(() => next())”

The mysterious secret will be revealed now. Do we really need to learn generators and use them in handy?

The answer is NOOOO!

generators

Because we have a more power tool “Async/await” which holds best due to its powerful features. Async/await is built using generators. Without these generators, Async/await will not work at all. But that doesn’t mean we do need to use and learn generators in our code. Generators are more complex. Let the framework and library developers use these generators to create more powerful modules like Async/await. The side benefit from the generator what we could say is “Easier Testing”. The famous bundler ”Brunch”, the interpreter “Co” and “Redux-Saga” make use of these generators specifically.

async-await

Reference Links:

 

Learn RxJS in 1 Blog…(Disclaimer: Javascript basics are highly recommended)

RxJS (stands for Reactive Javascript) is actually a well-known library that is used to handle asynchronous calls with multiple events. There are plenty of other reactive libraries written in other platforms. Some of them are RxJava, Rx.NET, UniRx, RxScala, RxClosure, RxCpp, RxPY, RxDart, RxNetty, RxAndroid, RxCocoa etc.

Sample RxJS Implementation:

const interval = new Observable(observer => {

 let count = 0;

 const interval = setInterval(() => {

   observer.next(count++);

 }, 1000);

 // once we stop listening to values clear the interval

 return () => {

   clearInterval(interval);

 }

});

interval.subscribe(value => console.log(value));

// —-1—-2—-3—->

The functional units of RxJs are,

Observable:

Observables are collections of a stream of values or events. It can hold either synchronous or asynchronous stream of values or events.

Observer:

After fetching the necessary values from observables, callbacks are implemented to perform the required actions based upon the values. These set of collections of callbacks are called observers.

Subscription:

Subscription is the way to return the value when the asynchronous function is completed.

Operators:

RxJs Operators can be considered as Lodash for events. It provides the ease of RxJS implementations through enabling functional programming.

Subject:

A subject is simply a unit that can act as both Observable and Observer simultaneously.

Schedulers:

Schedulers help us to define in what execution way does an observable deliver its values to the observer.

Basically, the RxJs Observables can be compared with Promises in a better way as they have the major similarities.

Reference Links: