Search code examples
angularangular-reactive-forms

How to check if my form array has the object already


I have an Angular Reactive form, something like this:

  profileForm = this.fb.group({
      firstName: new FormControl(''),
       lastName: new FormControl(''),
       address: this.fb.group({
          input: new FormArray([])
      }),
  });

and I have one object, something like this:

obj = {
    teste1: 'teste1',
    teste2: 0,
    teste3: 1,
  };

I want this kind of response:

profileForm = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    address: [
      { id: teste1, value: 'teste1' },
      { id: teste2, value: 0 },
      { id: teste3, value: 'teste2' },
    ],
  });

So I have a method that has a obj as param, and I need to verify if the array has already the obj, only update the value, if not, create a new object. so I tried:

  get addressArray() {
        return this.profileForm.get('address').get('input') as FormArray;
      }

    toDo(objParam) { //logic comes here
        Object.entries(obj).forEach(([key, value]) => {
          if(true){
            this.addressArray?.get(key)?.setValue(value);
          } else {
            this.addressArray.push(this.fb.control({[key] : value});
          }
        });
      }

you can see the code here


Solution

  • I'm a little confused between you wanna update the profileForm and push into it's addressArray. Is this correct or if you want to update the current addressArray, too?

    To check if the object exists you can use this.profileForm.controls[key]

    toDo(objParam) {
        Object.entries(objParam).forEach(([key, value]) => {
          if (this.profileForm.controls[key]) {
            this.profileForm?.get(key)?.setValue(value);
          } else {
            this.addressArray.push(this.fb.control({ [key]: value }));
          }
        });   
      }
    

    UPDATE

    This code will check if any object exists in addressArray.

      toDo(objParam) {
        console.log(this.addressArray)
        Object.entries(objParam).forEach(([key, value]) => {
          let found = false;
          for (let data of this.addressArray.controls) {
            if ((data as FormGroup).controls[key]) {
              found = true;
              break;
            }
          }
    
          if (found) {
            this.addressArray.controls.find(f => (f as FormGroup).controls[key] as FormGroup).get(key).setValue(value)
          } else {
            this.addressArray.push(this.fb.group({[key]: this.fb.control( value )}));
          }
        });  
      }