Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2/4 : Reactive forms are synchronous while template-driven forms are asynchronous, How?

I was going through the doc of angular.io (Reactive forms are synchronous), trying to understand the reactive forms (how they are synchronous and template driven forms are asynchronous).

But the doc doesn't have enough explanation with example . Can anyone help me understand how template driven forms are asynchronous and reactive forms are synchronous?

I tried to explore a lot of blogs on the internet but didn't get an answer.

Any help is appreciated.

like image 401
shreyansh Avatar asked Apr 05 '18 05:04

shreyansh


Video Answer


1 Answers

Read this line careful in same documentation :

Reactive forms are synchronous (as you create controls from you code) In reactive forms, you create the entire form control tree in code. You can immediately update a value or drill down through the descendants of the parent form because all controls are always available.

template-driven forms are asynchronous (as it delegate task of creation of control) Template-driven forms delegate creation of their form controls to directives. To avoid "changed after checked" errors, these directives take more than one cycle to build the entire control tree. That means you must wait a tick before manipulating any of the controls from within the component class.


In template driven from you write [NgModel] or [NgForm] (directives) that will take task of creation of your control on web page in html, that is how it becomes asynchronous.

If you attached hook ngAfterViewInit lifecycle hook you will find difference between them easily ,

In Reactive forms you find control where in Template driven from you dont.

like image 195
Pranay Rana Avatar answered Sep 27 '22 21:09

Pranay Rana