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

こ雲淡風輕ζ 提交于 2020-02-28 07:42:30

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/49665096/angular-2-4-reactive-forms-are-synchronous-while-template-driven-forms-are-asy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!