In the development process, I am currently working on breaking down a large component that retrieves data from a selected record and loads it into a FormGroup using FormBuilder.
My goal is to divide this component into reusable services and child components.
One of the key functions in the component is responsible for adding a new row to a FormArray. At the moment, this function is specific to the component itself.
Now my question is how can I refactor this function so that it can be moved to a service or another solution where it can be used across multiple components?
I want to avoid duplicating the logic by reusing the same function, however, since the function relies on the 'this' keyword to access the current context, I'm not sure how to make it reusable in a service.
The code snippet below represents the function I'm looking to move into a reusable service, considering that there are other similar functions in the component that also use the 'this' keyword:
TS Component
constructor(
private fb: FormBuilder
) { }
/**
* Add a new element to a form control array
* @param {string} formCtrlArrayName name of the form control array
* @param {string} valueToAdd element to add to the form control array
*/
public onAddRow(formCtrlArrayName: string, valueToAdd: any) {
this[formCtrlArrayName].push(this.fb.control(valueToAdd));
}
HTML Component
<button mat-button attr.aria-label="Add Assigned To" matTooltip="Add Assigned To"
(click)="onAddRow('AssignedTo', '', '')">
<mat-icon>add_circle</mat-icon>
</button>