tengo la siguiente clase, "import { Location } from "@angular/common";
import { Component, OnInit, Injector } from "@angular/core";
import { FormArray, FormBuilder, Validators } from "@angular/forms";
import { MatDatepickerInputEvent } from "@angular/material/datepicker";
import { CatalogService } from 'src/app/services/catalog/catalog.service';
import { MatDialog } from "@angular/material/dialog";
import { MatSelectChange } from "@angular/material/select";
import { MatSlideToggleChange } from "@angular/material/slide-toggle";
import { MatSnackBar } from "@angular/material/snack-bar";
import { Router } from "@angular/router";
import { delay, finalize } from "rxjs/operators";
import { CompanyDetail } from "src/app/models/company.models";
import {
  BodyRegisterContract,
  ListVehicle,
  ResponseContractRegister
} from "src/app/models/contract-company.models";
import { Brands, Models, VehicleType } from "src/app/models/vehicle.models";
import { CompaniesService } from "src/app/services/companies/companies.service";
import { HeaderService } from "src/app/services/header/header.service";
import { VehicleService } from "src/app/services/vehicle/vehicle.service";
import { ModalContractOkComponent } from "../modal-contract-ok/modal-contract-ok.component";
import { dataPersonGroupValidator } from "src/app/utils/validators/dataPersonRequiredValidator";
import { City } from "src/app/models/catalog.models";
import { MatCheckboxChange } from "@angular/material/checkbox";

@Component({
  selector: 'impulsa-new-contract',
  templateUrl: './new-contract.component.html',
  styleUrls: ['./new-contract.component.scss'],
})
export class NewContractComponent implements OnInit {
  loading = true;
  loadingRegister = false;
  companyDetail: CompanyDetail;
  companyName: string;
  listVehicleTypes: VehicleType[] = [];
  cities: City[] = [];
  documentsList: any;
  actualDate = new Date();
  range = 50;

  firstFormGroup = this._formBuilder.group(
    {
      startDate: ['', Validators.required],
      endDate: ['', Validators.required],
      billingCity: ['', Validators.required],
      automaticCharge: [],
      dataPerson: this._formBuilder.group({
        names: [''],
        surnames: [''],
        documentType: [''],
        documentNumber: [''],
        phone: [''],
        hour: [''],
      }),
    },
    { validator: dataPersonGroupValidator }
  );

  formVehiculos = this._formBuilder.group({});
  formServices = this._formBuilder.group({});

  newVehicleForm = this._formBuilder.group({
    brand: ['', Validators.required],
    vehicleModelId: ['', Validators.required],
    quanty: ['', Validators.required, Validators.min(1)],
    cityCode: ['', Validators.required],
    price: ['', Validators.required],
  });

  listBrand: any[] = [];
  listModel: any[] = [];
  listModelServices: any[] = [];
  listCities: any[] = [];
  listQuantityAvailable: number[] = [];
  listErrorMessage: string[] = [];
  body: BodyRegisterContract;

  public listHours: any = [
    { id: '7:40am', item: '7:40 a.m.' },
    { id: '8:00am', item: '8:00 a.m.' },
    { id: '8:20am', item: '8:20 a.m.' },
    { id: '8:40am', item: '8:40 a.m.' },
    { id: '9:00am', item: '9:00 a.m.' },
    { id: '9:20am', item: '9:20 a.m.' },
    { id: '9:40am', item: '9:40 a.m.' },
    { id: '10:00am', item: '10:00 a.m.' },
    { id: '10:20am', item: '10:20 a.m.' },
    { id: '10:40am', item: '10:40 a.m.' },
    { id: '11:00am', item: '11:00 a.m.' },
    { id: '11:20am', item: '11:20 a.m.' },
    { id: '11:40am', item: '11:40 a.m.' },
    { id: '12:00pm', item: '12:00 p.m.' },
    { id: '12:20pm', item: '12:20 p.m.' },
    { id: '12:40pm', item: '12:40 p.m.' },
    { id: '01:00pm', item: '01:00 p.m.' },
    { id: '01:20pm', item: '01:20 p.m.' },
    { id: '01:40pm', item: '01:40 p.m.' },
    { id: '02:00pm', item: '02:00 p.m.' },
    { id: '02:20pm', item: '02:20 p.m.' },
    { id: '02:40pm', item: '02:40 p.m.' },
    { id: '03:00pm', item: '03:00 p.m.' },
    { id: '03:20pm', item: '03:20 p.m.' },
    { id: '03:40pm', item: '03:40 p.m.' },
    { id: '04:00pm', item: '04:00 p.m.' },
    { id: '04:20pm', item: '04:20 p.m.' },
  ];
  step = 0;
  listVehiclesTypesServices: any[] = [];
  listInfoResume: any[] = [];
  total: number = 0;
  listServices = {
    basic: { services: [] },
    check: { services: [] },
  };
  listAddServices: any[] = [];

  private companiesService: CompaniesService;
  private catalogService!: CatalogService;
  private vehiclesService: VehicleService;
  private header: HeaderService;

  constructor(
    private injector: Injector,
    private _formBuilder: FormBuilder,
    private router: Router,
    private location: Location,
    private dialog: MatDialog,
    private snackBar: MatSnackBar
  ) {
    this.companiesService =
      this.injector.get<CompaniesService>(CompaniesService);
    this.catalogService = this.injector.get<CatalogService>(CatalogService);
    this.vehiclesService = this.injector.get<VehicleService>(VehicleService);
    this.header = this.injector.get<HeaderService>(HeaderService);
  }

  ngOnInit(): void {
    this.validatePath();
    this.fillListVehicleTypes();
    this.getDocumentTypes();
    this.getCities();
  }

  getDocumentTypes() {
    this.catalogService.getDocumentTypes().subscribe(
      (response: any) => {
        this.documentsList = response;
      },
      (error) => {
        console.dir(error);
      }
    );
  }

  validatePath() {
    if (!this.companiesService?.getCompanyDetail()) {
      this.router.navigate(['/dashboard/companies']);
      return;
    }
    this.companyDetail = this.companiesService.getCompanyDetail();
    this.companyName = this.companyDetail.data.name;
    this.header.updateTitle(' ');
    this.header.updateSubtitle('Empresas / Detalle empresa');
  }

  public changeEndDate(
    _event: MatDatepickerInputEvent<Date>,
    nameControl: string
  ) {
    const endDate = new Date(
      this.firstFormGroup.get('endDate').value
    ).getTime();
    const startDate = new Date(
      this.firstFormGroup.get('startDate').value
    ).getTime();
    if (startDate - endDate > 0) {
      this.firstFormGroup.get(nameControl).setErrors({ errorDateInit: true });
    }
  }

  fieldIsValid(field: string): boolean {
    return (
      this.firstFormGroup.controls[field].errors &&
      this.firstFormGroup.controls[field].touched
    );
  }

  getMessageErrorForm1(field: string): string {
    const errors = this.firstFormGroup.get(field)?.errors;

    if (errors.required) {
      return '* Campo obligatorio';
    }
    if (errors?.errorDateInit) {
      return 'Fecha inicio mayor a fecha fin';
    }
    return '';
  }

  public goBack(): void {
    this.location.back();
  }

  resetForm1() {
    this.goBack();
  }

  public fillListVehicleTypes(): void {
    this.companiesService.getListVehicleTypes().subscribe((res) => {
      this.listVehicleTypes = res;
      this.fillListBrandVehicles();
      this.loading = false;
      this.listVehicleTypes.forEach((type) => {
        this.formVehiculos.addControl(
          type.name,
          this._formBuilder.group({
            id: [type.id],
            active: [false],
            vehicles: this._formBuilder.array([]),
          })
        );
      });
      this.formVehiculos.updateValueAndValidity();
    });
  }

  public changeVehicleType(change: MatSlideToggleChange): void {
    if (this.getVehiclesForm(change.source.name).length === 0) {
      this.addVehicle(change.source.name);
    }
    if (
      this.getVehiclesForm(change.source.name).length > 0 &&
      !change.checked
    ) {
      this.getVehiclesForm(change.source.name).reset();
      for (
        let index = 0;
        index < this.getVehiclesForm(change.source.name).length;
        index++
      ) {
        this.delete(change.source.name, index);
      }
      this.formVehiculos.get(change.source.name).get('active').setValue(false);
    }
  }

  public valueControlVehicleForm(nameForm: string, contrl: string): any {
    return this.formVehiculos.get(`${nameForm}.${contrl}`).value;
  }
  public valueControlServicesForm(nameForm: string, contrl: string): any {
    return this.formServices.get(`${nameForm}.${contrl}`).value;
  }

  getVehiclesForm(nameFormGroup: string): FormArray {
    return this.formVehiculos.get(`${nameFormGroup}.vehicles`) as FormArray;
  }
  getVehiclesServicesForm(nameFormGroup: string): FormArray {
    return this.formServices.get(`${nameFormGroup}.vehicles`) as FormArray;
  }

  public changeBrandSelect(
    event: MatSelectChange,
    id: number,
    index: number,
    nameFormGroup: string
  ): void {
    this.vehiclesService.getModel(id, event.value).subscribe((resp: Models) => {
      const aux = resp.data.filter((x) => x.vehicle_type == id);
      this.listModel[id * this.range + index] = aux;
      this.listModelServices[id] = aux;
      this.listCities[id * this.range + index] = [];
      this.getVehiclesForm(nameFormGroup)
        .controls[index].get('cityCode')
        .setValue('');
      this.getVehiclesForm(nameFormGroup)
        .controls[index].get('vehicleModelId')
        .setValue('');
    });
  }

  public changeModelSelect(
    event: MatSelectChange,
    id: number,
    index: number,
    nameFormGroup: string
  ) {
    this.vehiclesService
      .getCitiesAvaliableForVehicleModel(event.value, 'OPERATIONAL_FLEET')
      .subscribe((resp) => {
        this.listCities[index + id * this.range] = resp.data;
        if (resp.data == null) {
          this.getVehiclesForm(nameFormGroup)
            .at(index)
            .get('cityCode')
            .setValue('');
          this.getVehiclesForm(nameFormGroup)
            .at(index)
            .get('cityCode')
            .setErrors({ notCity: true });
        }
      });
  }

  public changeCitySelect(
    event: MatSelectChange,
    id: number,
    index: number,
    formGroupName: string
  ) {
    const vehicleModel = this.getControlVehicle(
      formGroupName,
      'vehicleModelId',
      index
    );

    this.vehiclesService
      .getQuantityVehicleAvailableForCityAndModel(
        event.value,
        vehicleModel,
        'OPERATIONAL_FLEET'
      )
      .subscribe((resp) => {
        this.listQuantityAvailable[id * this.range + index] =
          resp.data.availability > 0 ? resp.data.availability : 0;
      });
  }

  addVehicle(nameFormGroup: string) {
    const newformVehicle = this._formBuilder.group({
      brand: ['', Validators.required],
      vehicleModelId: ['', Validators.required],
      quanty: ['', Validators.required],
      cityCode: ['', Validators.required],
      price: ['', Validators.required],
    });
    this.getVehiclesForm(nameFormGroup).push(newformVehicle);
  }

  fillListBrandVehicles() {
    this.listVehicleTypes.forEach((type) => {
      this.vehiclesService
        .getBrandsPerVehicle(type.id)
        .subscribe((resp: Brands) => {
          this.listBrand[type.id] = resp.data;
        });
    });
  }

  public delete(formGroupName: string, index: number): void {
    this.getVehiclesForm(formGroupName).removeAt(index);
    if (this.getVehiclesForm(formGroupName).length === 0) {
      this.formVehiculos.get(formGroupName).get('active').setValue(false);
    }
  }

  public getControlVehicle(
    formGroupName: string,
    control: string,
    index: number
  ): any {
    return this.getVehiclesForm(formGroupName).controls[index].get(control)
      .value;
  }

  public getListVehicles(): ListVehicle[] {
    let listVehicles: ListVehicle[] = [];
    this.listVehicleTypes.forEach((type) => {
      if (this.valueControlVehicleForm(type.name, 'active')) {
        for (
          let index = 0;
          index < this.getVehiclesForm(type.name).length;
          index++
        ) {
          listVehicles.push(this.getVehiclesForm(type.name).at(index).value);
        }
      }
    });
    return listVehicles;
  }

  public createContract(): void {
    if (this.formVehiculos.invalid) {
      this.formVehiculos.markAllAsTouched();

      return;
    }
    if (this.getListVehicles().length === 0) {
      this.snackBar.open('Debe registrar vehiculos', null, {
        duration: 2000,
      });
      return;
    }
    let contractManager: any = {};
    
    this.body = {
      clientDocumentType:
        this.companyDetail.data.tipoIdentificacionC == 'NIT' ? 'N' : '',
      clientDocumentNumber: this.companyDetail.data.numeroIdentificacionC,
      startDate: this.firstFormGroup.get('startDate').value,
      endDate: this.firstFormGroup.get('endDate').value,
      listVehicles: this.getVehiclesToServices(),
      billingCity: this.firstFormGroup.get('billingCity').value,
      automaticCharge: this.firstFormGroup.get('automaticCharge').value,
    };
  
    if (this.isDataPersonFilled()) {
      {
        contractManager.names = this.firstFormGroup
          .get('dataPerson')
          .get('names').value;
        contractManager.surnames = this.firstFormGroup
          .get('dataPerson')
          .get('surnames').value;
        contractManager.documentNumber = this.firstFormGroup
          .get('dataPerson')
          .get('documentNumber').value;
        contractManager.documentType = this.firstFormGroup
          .get('dataPerson')
          .get('documentType').value;
        contractManager.hourDelivery = this.firstFormGroup
          .get('dataPerson')
          .get('hour').value;
        contractManager.phone = this.firstFormGroup
          .get('dataPerson')
          .get('phone').value;
        this.body.contractDeliveryManager = contractManager;
      }
    }
    this.loadingRegister = true;
    this.companiesService
      .registerContract(this.body)
      .pipe(delay(2000))
      .subscribe(
        (resp) => {
          this.loadingRegister = false;

          if (resp.data.process) {
            const dialogRef = this.dialog.open(ModalContractOkComponent, {
              disableClose: true,
              autoFocus: false,
            });

            dialogRef.afterClosed().subscribe((_resp) => {
              this.router.navigate([
                `dashboard/companies/detail/${this.companyDetail.data.id}/contracts`,
              ]);
            });
          }
        },
        (error) => {
          this.loadingRegister = false;
          if (error.status != 400) {
            this.snackBar.open('Error al registar anexo', null, {
              duration: 3000,
            });
            return;
          }

          const errorResponse: ResponseContractRegister = error.error;
          this.setErrorResponse(errorResponse);

          this.snackBar.open(
            'La cantidad de vehículos supera la disponibilidad de inventario',
            'x',
            {
              duration: 3000,
              panelClass: 'snack',
            }
          );
        }
      );
  }

  public notFieldValid(
    nameFormGroup: string,
    field: string,
    index: number
  ): boolean {
    return (
      this.getVehiclesForm(nameFormGroup).at(index).get(field).errors &&
      this.getVehiclesForm(nameFormGroup).at(index).get(field).touched
    );
  }

  public setErrorResponse(error: ResponseContractRegister): void {
    this.listVehicleTypes.forEach((type) => {
      this.getVehiclesForm(type.name);
      for (
        let index = 0;
        index < this.getVehiclesForm(type.name).length;
        index++
      ) {
        error.data.listVehiclesErrors.forEach((vehicleError) => {
          if (
            vehicleError.vehicleModelId ===
            this.getVehiclesForm(type.name).at(index).get('vehicleModelId')
              .value
          ) {
            this.getVehiclesForm(type.name)
              .at(index)
              .get('quanty')
              .setErrors({ errorQuanty: true });
            this.listErrorMessage[
              this.valueControlVehicleForm(type.name, 'id') + index
            ] = `${vehicleError.available} vehículos disponibles`;
          }
        });
      }
    });
  }

  getErrorMessage(nameFormGroup: string, field: string, index: number) {
    const errors = this.getVehiclesForm(nameFormGroup)
      .at(index)
      .get(field)?.errors;
    if (errors?.errorQuanty) {
      return this.listErrorMessage[
        this.valueControlVehicleForm(nameFormGroup, 'id') + index
      ];
    }

    if (errors?.notCity) {
      return '* No hay vehículos disponibles';
    }
    if (errors?.required) {
      return '* Campo obligatorio';
    }

    return '';
  }

  public isValidFormStatus(): boolean {
    let existVehicles = [];
    existVehicles = this.listVehicleTypes.filter((type) => {
      return (
        this.getVehiclesForm(type.name).length > 0 &&
        this.formVehiculos.get(`${type.name}.active`).value
      );
    });

    return existVehicles.length > 0 && this.formVehiculos.valid;
  }

  getCities() {
    this.catalogService.getCitiesEnabled().subscribe({
      next: (res: any) => {
        this.cities = res.data;
      },
    });
  }

  private isDataPersonFilled(): boolean {
    const dataPerson = this.firstFormGroup.get('dataPerson').value;
    return Object.values(dataPerson).some(
      (value) => value !== null && value !== ''
    );
  }

  public fillServicesForm() {
    this.step = 3;
    this.formServices = this._formBuilder.group({});
    let isactive = true;
    Object.keys(this.formVehiculos.value).forEach((type) => {
      if (this.formVehiculos.get(`${type}.active`).value) {
        const vehicle = this.listVehicleTypes.find((v) => v.name == type);
        this.listVehiclesTypesServices.push(vehicle);
        this.formServices.addControl(
          type,
          this._formBuilder.group({
            id: [vehicle ? vehicle.id : 0],
            active: [isactive],
            vehicles: this._formBuilder.array([]),
          })
        );
        isactive = false;
      }
      this.formServices.updateValueAndValidity();
    });
    this.fillInfoVehiclesToEdit();
    this.getServicesAditionals();
  }

  addVehicleServices(nameFormGroup: string, vehicle?: any, index?: number) {

    const newformVehicle = this._formBuilder.group({
      brand: vehicle.brand,
      vehicleModelId: vehicle.vehicleModelId,
      telemetryBasic: false,
      telemetryPreo: false,
    });
    this.getVehiclesServicesForm(nameFormGroup).push(newformVehicle);
  }

  fillInfoVehiclesToEdit() {
    this.total = 0;
    this.listInfoResume.push({ name: 'Vehiculos', items: [] });
    Object.keys(this.formVehiculos.value).forEach((type: any) => {
      
      if (this.formVehiculos.get(`${type}.active`).value) {
        if (this.getVehiclesForm(type).length > 0) {
          this.formVehiculos
            .get(`${type}.vehicles`)
            .value.forEach((element, index) => {
              const value = element.price * element.quanty;
              this.total += value;
              this.listInfoResume[0].items.push({
                name: `${this.getnameBrand(
                  this.formVehiculos.get(`${type}.id`).value,
                  element.brand
                )} ${this.getNameModel(
                  this.formVehiculos.get(`${type}.id`).value,
                  element.vehicleModelId
                )}`,
                desc: `$ ${element.price} x ${element.quanty}`,
                value: value,
              });
              this.addVehicleServices(type, element);
            });
        }
      }
    });
    this.listInfoResume.push({
      name: 'Servicios adicionales',
      items: [
        { name: 'Telemetría básica', value: 0 },
        { name: 'Telemetría + Chequeo preoperacional', value: 0 },
      ],
    });
  }

  getVehiclesToServices(): any[] {
    let listVehicles: any = [];
    for (let key in this.formServices.value) {
      this.getVehiclesServicesForm(key).value.forEach((vehicle, i)=> {
        const vehicleform = this.getVehiclesForm(key).value[i];
        if (vehicle.telemetryBasic) {
          const vehicleWithService = {
            ...vehicleform,  
            listServiceAditionals: [this.listServices.basic.services[this.valueControlServicesForm(key, 'id')-1].id]  
          };
          listVehicles.push(vehicleWithService);
          return;
        }
        if (vehicle.telemetryPreo) {
          const vehicleWithService = {
            ...vehicleform,  
            listServiceAditionals: [this.listServices.check.services[this.valueControlServicesForm(key, 'id')-1].id] 
          };
          listVehicles.push(vehicleWithService);
          return;
        }
        listVehicles.push(vehicleform);
      });
    }
    return listVehicles;
  }

  getnameBrand(vehicleType: number, id: number): string {
    let brand: any;
    brand = this.listBrand[vehicleType].find(
      (item: { name: string; brand: number }) => {
        return item.brand === id;
      }
    );
    return brand.name;
  }

  getNameModel(vehicleType: number, id: number): string {
    let model: any;
    model = this.listModelServices[vehicleType].find((item) => {
      return item.id === id;
    });
    return model.reference;
  }

  changeServicesTelemetry(
    event: MatCheckboxChange,
    value: string,
    id: number,
    index: number,
    type: string
  ): void {

    if (event.checked) {
      if (value == 'basic') {
        this.listInfoResume[1].items[0].value +=
          this.listServices.basic.services[id - 1].price *
          this.getVehiclesForm(type).value[index].quanty;
          this.getVehiclesServicesForm(type)[index].push({price:['', Validators.required]});
      }else{
        this.listInfoResume[1].items[1].value +=
          this.listServices.check.services[id - 1].price *
          this.getVehiclesForm(type).value[index].quanty;
      }
    }else{
      if (value == 'basic') {
        this.listInfoResume[1].items[0].value -=
          this.listServices.basic.services[id - 1].price *
          this.getVehiclesForm(type).value[index].quanty;
      }else{
        this.listInfoResume[1].items[1].value -=
          this.listServices.check.services[id - 1].price *
          this.getVehiclesForm(type).value[index].quanty;
      }
    }
  }

  getServicesAditionals() {
    this.loading = true;
    this.vehiclesService
      .getServicesKeyService('SERVICE_ADDITIONAL_FO')
      .pipe(finalize(() => (this.loading = false)))
      .subscribe({
        next: (res) => {
          this.listServices.basic.services = res.data.slice(0, 4);
          this.listServices.check.services = res.data.slice(4, 8);
        },
      });
  }

  bort(){
    console.log('abort')
  }
}
" necesito que apenas se active el checkbox que controla la propiedad telemetryPreo o la propiedad telemetryBasic agregue un nuevo control al formulario llamado price, para que ese formulario quede algo asi "const newformVehicle = this._formBuilder.group({
      brand: vehicle.brand,
      vehicleModelId: vehicle.vehicleModelId,
      telemetryBasic: false,
      telemetryPreo: false,
      price:['', Validators.required]
    });" sin embargo no he podido, y hay q tener en cuenta que seria un metodo dinamico para poder agregarle al nuevo campo al formulario por nombre e index del formulario de vehiculos