使用patchValue对模板驱动的表单进行初始化 [英] Initialize using patchValue for template driven forms
问题描述
我使用模板驱动,并试图使用patchValue初始化表单,但它不起作用.
I use template driven and am trying to initialize my form using patchValue and it is not working.
如果我使用双向绑定设置值[[fooBar)]甚至setTimeout都可以使它工作,但我只是想知道,有没有一种方法可以使它仅与patchValue一起工作?
I can make it work if I use two-way binding to set values [(fooBar)] or even setTimeout but I was just wondering, is there a way to make it work with just patchValue?
https://stackblitz.com/edit/angular-fft2c5
谢谢.
推荐答案
它不起作用,因为在调用时 patchValue
方法您的帐户中未注册任何控件表格.
It doesn't work because at the time of calling patchValue
method there are no any controls registered in your form yet.
为什么?
这是因为模板驱动的表单是异步.他们将其窗体控件的创建委托给指令.为了避免检查后更改"错误,这些指令花费了一个以上的周期来构建整个控制树.这意味着在操作组件类中的任何控件之前,您必须先打勾.
That's because Template-driven forms are asynchronous. They 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.
此外,如果尝试使用setValue
方法而不是patchValue
,Angular甚至会警告您如何处理它.
Moreover, if you try using setValue
method instead of patchValue
Angular will even warn you how to deal with it.
this.myForm.control.setValue({name: this.name});
错误错误:没有向该组注册任何表单控件 然而.如果您使用的是ngModel,则可能要检查下一个勾号(例如 使用setTimeout).
ERROR Error: There are no form controls registered with this group yet. If you're using ngModel, you may want to check next tick (e.g. use setTimeout).
因此,正如您已经发现的那样,您必须使用[ngModel]
绑定,或者使用例如setTimeout
或requestAnimationFrame
So, as you already discovered, you have to either use [ngModel]
binding or wait next tick by using e.g setTimeout
or requestAnimationFrame
如果要在ngAfterViewInit挂钩中使用微任务,也应该计划微任务:
Scheduling microtask should also work if you would use it in ngAfterViewInit hook:
ngAfterViewInit() {
Promise.resolve().then(() => {
this.myForm.control.patchValue({ name: this.name });
});
}
这篇关于使用patchValue对模板驱动的表单进行初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!