My Scenario: My products have variations and each variation can have "N" attributes.
I made the addition of the variations with the formgroup array:
createFormGroup(){
return this.fb.group({
atributo: "",
preco: null,
listaatributos: [{id: null, tipovariacao: null, valorvariacao: null}]
}
Note that my array lists attributes are the attributes that can have "N" for each variation.
To add a variation, I use this function:
addVariacao(): void {
this.variacoes.push(this.createFormGroup());
}
And to show in the template the added variation I use this * ngFor:
<form *ngIf="mostraVariacoes" [formGroup]="variacaoForm">
<ng-container *ngFor="let item of variacoes.controls; let i = index;">
<div [formGroup]="item">
My function that adds attribute in the template receives as a parameter the index of the variation that I want to add the attribute:
adicionaAtributo(i)"
In my typescript it is declared as follows:
adicionaAtributo(index: number){ //Adiciona atributo no form group
this.listAtributos.push({indexvariacaoatributo: index, id:this.idAtributo, tipovariacao: this.variacaoForm.value.variacoes[index].tipo, valorvariacao: this.variacaoForm.value.variacoes[index].atributo})
const control = (<FormArray>this.variacaoForm.controls['variacoes']).at(index);
control.patchValue({listaatributos: this.listAtributos});
console.log(this.listAtributos);
}
and in my template I show it as follows:
<div class="row">
<div [hidden]="atributos.indexvariacaoatributo != i" *ngFor="let atributos of item.value.listaatributos;let indexatributo = index" class="col-6 col-md-4 alinhacentral animated zoomIn">
<div *ngIf="atributos.indexvariacaoatributo == i">
<span class="tituloAtributo">{{atributos.tipovariacao}}</span> <i (click)="removeAtributo(i,indexatributo)" class="fa fa-close iconeexcluiatributo"
aria-hidden="true"></i>
<br>
<span class="atributo">{{atributos.valorvariacao}}</span>
</div>
</div>
</div>
My problem currently lies in excluding variation. For example, I have variation 1 with the attribute:
Cor: Azul.
In variation 2 with the attribute:
Cor: Amarelo
When I call the function to exclude the variation that corresponds to the yellow color attribute, everything works fine, the first variation persists with its "Blue" attribute.
But when I exclude the first variation, the second variation fails to show the attributes.
This is my function that excludes variation:
removeVariacao(index: number) { //Primeiro remove todos os atributos daquela variação para depois remover a variação
for(let i=0;i<this.listAtributos.length;i++){
if(this.listAtributos[i].indexvariacaoatributo == index){
this.listAtributos.splice(i,1);
i--; //evita que ele ignore o próximo elemento
}
}
this.variacoes.removeAt(index);
}
I think the problem is something in my ngfor to show the attributes, but I can not identify what.
If anyone can help me, I'll be grateful.