Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
angular checkboxes with 2 dimensional array

I have a template:

<mat-card *ngFor="let cargo of cargos" class="cont-mat">
    /*...*/
<form [formGroup]="cargoSignupForm" (submit)="onSignupForCargo(cargo.id)" *ngIf="!isLoading">
                                          <p>Odaberite kamione s kojima želite izvršiti prijevoz - Težina robe: {{cargo.weight}} kg</p>
                                          <div *ngFor="let truck of (trucksByCargoId.get(cargo.id))">
                                            <input type="checkbox" (change)="onChange(truck._id, $event.target.checked, cargo.id)">{{truck.regNumber}}
                                          </div>
                                          <input type="submit" value="GO" class="button-basic">
                                        </form>

and 2 component functions:

truckFormArray = [[]];

ngOnInit() {
/*...*/
    this.cargoSignupForm = new FormGroup({
            trucksId: this.fb.array([])
          });
/*...*/
}

onChange(truckId: string, isChecked: boolean, cargoId: string) {
    this.truckFormArray[cargoId] = <FormArray>this.cargoSignupForm.controls.trucksId;
    if (isChecked) {
      this.truckFormArray[cargoId].push(new FormControl(truckId));
    } else {
      let index = this.truckFormArray[cargoId].controls.findIndex(x => x.value == truckId)
      this.truckFormArray[cargoId].removeAt(index);
    }
  }

  onSignupForCargo(cargoId: string) {
      console.log(this.truckFormArray[cargoId]);
  }

I just want to console_log(this.truckFormArray[cargoId]). There must be different truckFormArray for every cargoId. With that solution I'm getting trucksFormArray from previus cargoId checkboxes also. I hope you understand what I mean. Somewhere is a small mistake, but also if you think there is a better solution to do that you are welcome. Thanks in advance

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

truckFormArray should be an object

It is safe to assume that cargoId is not a sequentially increasing number starting from 0, hence there is no sense in declaring it as an array, declare it as an object instead:

truckFormArray = {};

Reason: Arrays in Javascript are always indexed by numbers starting from 0 and increasing sequentially until the last index.

truckFormArray is not a data member of the instance of your object

Since it is not initialized as this.truckFormArray, you do not have the this in front of it. So change all occurrences of this.truckFormArray to truckFormArray.

Reason: You will always need to be consistent when you refer to your resources.

Initializing truckFormArray

You have

this.truckFormArray[cargoId] = <FormArray>this.cargoSignupForm.controls.trucksId;

and it seems to be incorrect. Your trucksId seems to be a number and you try to assign it to a resource which is treated as an array, so there is a type discrepancy. If you want to store each trucksId into an array identified by the cargo that is present on the trucks, then you need to do a push, but only if the checkbox is checked. So, instead of the above, you will need something like this:

if (!truckFormArray[cargoId]) {
    //Here I created a JS array for the sake of simplicity, but you can
    //create a FormArray instance instead if that's more helpful for you
    this.truckFormArray[cargoId] = [];
}

Reason: if the array you need to refer to does not exist yet, then you need to create it.

Summary

You will need to

  • fix the initialization of truckFormArray
  • ensure that you refer it consistently with the way it is defined
  • initialize each of its cargo array when needed
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda