[英]Populate default values of child forms in Angular CVA
I have an Angular 12 application (see source code on Stackblitz ) that uses reactive forms and a ControlValueAccessor pattern to create a series of "steps".我有一个 Angular 12 应用程序(请参阅Stackblitz上的源代码),它使用反应式 forms 和 ControlValueAccessor 模式来创建一系列“步骤”。 When I add steps manually (ie via the "Add Step" button) and fill in the step details, the parent form (
parentForm
) has the values of each added step as expected:当我手动添加步骤(即通过“添加步骤”按钮)并填写步骤详细信息时,父表单 (
parentForm
) 具有预期的每个添加步骤的值:
# "Step 0" details entered via web UI
# parentForm.value | json
{ "steps": [ { "name": "Step 0", "action": "action_one" } ] }
However, when I pre-populate the values of a step (as if I would if I were loading step values from an external service) those values show up in the UI but the associated element in parentForm.steps
is null:但是,当我预填充步骤的值时(就像我从外部服务加载步骤值一样)这些值显示在 UI 中,但 parentForm.steps 中的关联元素是
parentForm.steps
:
# "Step 0" prepopulated, "Step 1" details entered via web UI
# parentForm.value | json
{ "steps": [ null, { "name": "Step 1", "action": "action_one" } ] }
How do I get the prepopulated values for "Step 0" into parentForm
?如何将“步骤 0”的预填充值获取到
parentForm
?
Turns out all you need to do is pass the value to the FormControl
constructor in the parent Component.事实证明,您需要做的就是将值传递给父组件中的
FormControl
构造函数。 As shown in the (new) Stackblitz :如(新) Stackblitz 所示:
ngAfterContentInit() {
this.parentForm = new FormGroup({
name: new FormControl(),
url: new FormControl(),
steps: new FormArray([
// To give a default value to the child, pass an object containing
// the values of the child form fields to the FormControl constructor
new FormControl({ name: 'Step 1', action: 'blarg', value: '' }),
new FormControl(),
]),
});
this.changeDetectorRef.detectChanges();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.