Populate default values of child forms in Angular CVA

357 Views Asked by At

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". When I add steps manually (i.e. via the "Add Step" button) and fill in the step details, the parent form (parentForm) has the values of each added step as expected:

# "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:

# "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?

1

There are 1 best solutions below

0
On

Turns out all you need to do is pass the value to the FormControl constructor in the parent Component. As shown in the (new) 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();
  }