【发布时间】:2022-01-13 01:25:34
【问题描述】:
晚上好,我有一个问题,我使用的是反应式表单,使用 FormArray,我有一个按钮可以根据需要多次添加 2 个选项,问题是这些选项是 matselects,我在其中一个选择中使用一个事件(更改),问题是第一次添加选项 onchange 工作正常,但是当添加选项超过 2 倍时,之前在 matselects 中选择的值会发生变化,因为创建的 select 的 onchange 是 re -执行。 我想知道是否有办法在 formArray 的每次迭代中独立使用该事件
组件.ts
alicuotaForm: FormGroup;
value = this.fb.group({
manzana: ['', Validators.required],
villa: ['', Validators.required],
});
nregistros: number;
ngOnInit() {
this.alicuotaForm = this.fb.group({
times: this.fb.array([]),
});
}
//event onchange
getVillas(value) {
console.log('valor: ', value.value);
this.filtro = this.villas.filter((x) => x.manzana == value.value);
}
addGroup() {
const val = this.fb.group({
manzana: ['', Validators.required],
villa: ['', Validators.required],
});
const alicuotaForm = this.alicuotaForm.get('times') as FormArray;
alicuotaForm.push(val);
this.nregistros = alicuotaForm.length;
}
removeGroup(index) {
const alicuotaForm = this.alicuotaForm.get('times') as FormArray;
alicuotaForm.removeAt(index);
}
trackByFn(index: any, item: any) {
return index;
}
component.html
<div class="container">
<div class="row">
<div class="col-col-6">
<label class="transparente"></label>
<button (click)="addGroup()" type="button" class="btn btn-success">
Agregar Campos
</button>
</div>
<br />
<form [formGroup]="alicuotaForm">
<ng-container
formArrayName="times"
*ngFor="
let time of alicuotaForm.controls.times?.value;
let i = index;
trackBy: trackByFn
"
>
<ng-container [formGroupName]="i" style="margin-bottom: 10px;">
Iteracion {{ i + 1 }}
<div class="col-col-6">
<label>Manzana</label>
<select
formControlName="manzana"
class="form-control custom-select"
(change)="getVillas($event.target)"
>
>
<option *ngFor="let ur of manzanas">
{{ ur.manzana }}
</option>
</select>
</div>
<br />
<div class="col-sm">
<label>Villa</label>
<select formControlName="villa" class="form-control custom-select">
<option *ngFor="let ur of filtro" value="{{ ur.villa }}">
{{ ur.villa }}
</option>
</select>
</div>
<br />
------------------------------------------------------------------------<br /> </ng-container
></ng-container>
</form>
</div>
</div>
我不知道我能做什么或者你会建议我解决什么 我的问题,非常感谢
stackblitz 中的代码 Stackblitz
【问题讨论】:
标签: javascript angular typescript angular-reactive-forms formarray