Patch value not working with nested inputs Reactive forms Angular 5

Issue

I’m working with Angular 5 and reactive forms, mi form is been created dynamically with a JSON that is been provided by the backend, there are some special inputs that are nested 3 levels and it works great with radio buttons but when the inputs are group of nested checkbox the patch value do not change the value of the checkboxes, this an example of mi structure

this.cvForm = this._fb.group({
  name: ['', [Validators.required]],
  lastname: ['', [Validators.required]],
  nested: this._fb.group({
    level1: this._fb.group({
       level2: this._fb.group({
          level3: this._fb.group({
             checkbox: [false, Validators.required]
         })
       })
     }),
   }),
 });
}

 this.cvForm 
    .get([
      'nested',
      this.nested,
      'level1',
      this.level1,
      'level2',
      this.level2,
      'level3',
      this.level3,
      'components',
      checkbox
    ]).patchValue({ checked: setValue });

EDIT:

I’ve been doing a lot of test with examples that you guys provide and I appreciate all your help. But I saw that the patch value it’s not saving o changing the value at first click, when I click the checkbox once the view changes but the value in the form is still false and the second click on the checkbox set value to true in the form, but the view is changed so, basically the patch value and set value are setting the value till the second click in the form. And I have no idea why is that happening.

Solution

After several hours of research and testing I found that reactive forms in angular does not support the object.property syntax to set the value for depth level values, instead I did this:

this.cvForm.controls['nested'].controls['level1'].controls['level2'].controls['level3'].controls['checkbox'].value['checked'] = newValue;

That fix my problem, thanks guys for the help.

Answered By – GeekDev

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.