Home > Mobile >  How to push the array items to the array properties of form group
How to push the array items to the array properties of form group

Time:06-20

I have a form group defined as:

this.scheduleParentModel = this.fb.group({
    startDate: ['', dateValidator()],
    endDate: ['', dateValidator()],
    frequency: [1, Validators.required],
    repeatTime: ['', Validators.required],
    frequencyInterval: this.fb.array([],),

}, { validator: this.dateLessThan('startDate', 'endDate') });

After the API call, I wanted to bind the result from API into the form group scheduleParentModel . API also returns the frequencyinterval as a comma-separated string.

I have bind the api result as:

this.scheduleParentModel.patchValue({
    startDate: this.datepipe.transform(new Date(schedules.startdate), 'mediumDate'),
    endDate: this.datepipe.transform(new Date(schedules.enddate), 'mediumDate'),
    repeatTime: schedules.repeattime,
    frequency: schedules.frequency
});

for binding to the frequency interval, I did, as:

let frequencyInterval = [...schedules.frequencyinterval.split(',').map(item => item.trim())];
const fInt = this.scheduleParentModel.controls.frequencyInterval as FormArray;
fInt.push(this.fb.group(frequencyInterval));

it becomes as:

{
    "startDate": "Jun 24, 2022",
    "endDate": "Jun 30, 2022",
    "frequency": 8,
    "repeatTime": "18:00",
    "frequencyInterval": [{
        "0": "5",
        "1": "4",
        "2": "3",
        "3": "2",
        "4": "1"
    }]
}

however, i wanted the output as:

{
    "startDate": "Jun 24, 2022",
    "endDate": "Jun 30, 2022",
    "frequency": 8,
    "repeatTime": "18:00",
    "frequencyInterval": ["5","4","3","2","1"]
}

Schedule objects:

{
    "enddate": "2022-06-30T00:00:00",
    "frequency": 8,
    "frequencyinterval": "5, 4, 3, 2, 1",
    "lastUpdateOn": "2022-06-18T09:41:26",
    "message": "ffdsdewe",
    "remindafter": false,
    "remindtime": 0,
    "repeattime": "18:00",
    "scheduleid": 10,
    "startdate": "2022-06-24T00:00:00",
    "starttime": "",
    "timezone": null,
    "title": "reset donerecurring"
}

How to push the array items to the properties of form group.

CodePudding user response:

use this for binding to the frequency interval.

const fInt = this.scheduleParentModel.controls
  .frequencyInterval as FormArray;
let frequencyInterval = schedules.frequencyinterval
  .split(',')
  .forEach((item) => fInt.push(this.fb.control(item.trim())));  

you need to use control instead of group

  • Related