Search code examples
angulartypescriptangular-services

Move functions that use `this` keyword from a component into a shared service


I have a large component that loads data from a selected record into a FormGroup using FormBuilder.

I am in the process of splitting up this component into reusable services and child components.

I have a function that is called from the view to add a new row to a FormArray. This function takes the name of the array and the value to add.

This is working properly within the component.

Question: How can this function be moved to a service (or other solution) to make it reusable across many different components? In other words, I want to be able to use the onAddRow function across many components without having to re-write the logic repeatedly. Since this function makes use of the this keyword to access the current context, I am unsure how to move this to a reusable service.

Here is the component code that I am trying to be able to move into a service. Note that I have many other functions similar to onAddRow that use the this keyword and I want to be able to move everything into a reusable service.

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>

Solution

  • untested - writing off the cuff here but something like this should work:

    // this is some reusable code in a service etc
    public addRow(formCtrlArray: any, valueToAdd: any): any { // accept any, return any
      let myArray = <Array<any>>formCtrlArray;
      myArray.push(valueToAdd);
      return myArray;
    }
    

    then just call that from your component passing in the correct parameters...