What about some useful tips and tricks for angular reactive form?

Reading Time: 2 minutes

To build an application, it is quite frequent to take input from the user then angular reactive form comes into action. Here are some useful tricks and tips to make the angular reactive form more efficient and reliable.

To continue with this blog basic understanding of angular reactive form is required.

Prevent infinite loops

Sometimes we are with infinite loops in setting up of form controls. We can understand this with an example. For example, we created a situation where we listen to the store’s changes and update the form accordingly, and also we listen to the form’s value changes and update the store (Refer below code).

ngOnInit() {
  this.store.subscribe(storeVal => this.exampleForm.patchValue(storeVal));
  this.exampleForm.valueChanges.subscribe(changeVal => this.updateStore(changeVal));
}

To handle the above infinite loop situation, angular provides not to emit value changes event whenever form update.

this.exampleForm.patchValue(value, { emitEvent: false })

Disable form control

Sometimes in the initialization process, it is required to disable the form control. This can be done by passing an object to the FormControl constructor.

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

Here, as coders need to pay attention to that we must also pass the value property; otherwise Angular assumes that we want the control’s value to be { disabled: true }.

Also angular provides a method to disable and enable the controls.

control.enable()
control.disable()

For a surprise, angular trigger valueChange method on every call or control.enable() and control.disable(). Refer to the below code to understand this.

name.valueChanges.subscribe(() => {
  console.log('changed!!');
});

setTimeout(() => {
  name.enable();
}, 1000);

To handle this, we have already discussed an easy fix for this. We can add { emitEvent false } to the current method:

name.enable({ emitEvent: false });
name.disable({ emitEvent: false });

Optimized control validation check on change

As you know, whenever there is a value change, angular goes for a control validation check.

For example, if you have an input that is bound to a form control, Angular performs the control validation process for every keystroke (Refer to the below code).

export class AppComponent  {
  control = new FormControl(null, dummyValidator);
}

function dummyValidator(control: FormControl) {
  console.log('checking...')
  return null;
}

So, we can optimize this control validation check process, whenever change in form control data. We can proceed with the below refer code:

ngOnInit() {
  const name = this.group.get('name');

  name.valueChanges.pipe(
    debounceTime(300),
    untilDestroyed(this)
  ).subscribe(() => name.setErrors(Validators.minLength(2)(name)))
}

Every control exposes an valueChanges observable that we can take advantage of, and use RxJS to do some more powerful stuff. For example, we can add a debounce to our control.

Also, using the updateOn property, we can handle the above case (discussed in the next point).

Using UpdateOn

The problem we discussed in the previous heading can also be handled using updateOn property.

Now, you can imagine a complex validation requirement — updating such a form on every keystroke could become too complex and slow. Also, it is very annoying to display an error message to the user when he hasn’t completed the action of entering the form data.

We can tell Angular that we only want to run the validation function upon submit or blur.

export class AppComponent {

  control = new FormControl(null, {
    validators: Validators.minLength(4),
    updateOn: 'blur'
  });

With every blog we publish, our goal is to share knowledge to make confident and better coders.
For more tech blogs, please visit Knoldus Blogs. Also, please follow our LinkedIn page- FrontEnd Studio
Enjoy Coding…
To know more about angular please visit the angular document.