Есть ли способ присвоения переменных шаблону с индексом? В настоящее время, если я ввожу элемент, описание и единица измерения (UM) размещаются в правильном месте (подробности позже в посте), но если я добавляю еще один элемент, описание и UM дублируются в обоих местах. Я знаю, что это происходит, потому что у них одинаковое имя переменной, но я не уверен, что это хороший способ справиться с этим. Я думал, может быть, валидатор или что-то в этом роде, но я не был уверен, как это будет работать.
У меня есть страница реактивной формы, которую я переключаю с многокомпонентной формы на однокомпонентную. Я знаю, что могу добиться этого, используя два компонента, но у меня возникли проблемы с сбросом асинхронных данных после отправки формы с помощью многокомпонентного подхода.
У меня FormArray
заполняется функцией, которая возвращает FormGroup
:
this.myForm = this.fb.group({
...
requisitionItems: this.fb.array([this.initItems()])
});
initItems(): FormGroup {
return this.fb.group({
item: ['', Validators.required],
quantity: ['', Validators.required],
lot: [''],
reasonCode: ['', Validators.required],
operation: [{ value: '', disabled: true }]
});
}
У меня есть функция, которая принимает item: string
и возвращает описание и единицу измерения асинхронно. Описание отображается под полем ввода элемента, а единица измерения отображается рядом с полем ввода количества:
enterItem(item: string) : void {
if (item) {
this.itemServ.getItemDescription(item).subscribe(
res => {
this.itemDesc = res.toString();
},
err => {
this.itemDesc = 'Could not find this item';
}
);
this.itemServ.getUnitOfMeasure(item).subscribe(res => {
this.unitOfMeasure = res.toString();
});
}
В моем шаблоне у меня есть FormArray
, заполненный *ngFor
с индексом, и [formGroupName]="i"
. (Из соображений краткости лишние элементы и стили удалены)
<div formArrayName="requisitionItems" *ngFor="let item of requisitionItems.controls; let i = index" class="well" style="border: 1px solid black; border-radius: 10px; margin-top: 10px;" style="padding-bottom: 3px">
<div [formGroupName]="i">
<label attr.for="{{'item' + i}}">Matric Part #</label>
<input type="text" formControlName="item" id="{{'item' + i}}" (keyup.enter)="enterItem(item.value.item)" (blur)="enterItem(item.value.item)">
<span attr.for="{{'item' + i}}" class="smallspan" [ngStyle]="{'color':this.itemDesc === 'Could not find this item' ? 'red' : 'black' }">{{this.itemDesc}}</span>
<label attr.for="{{'quantity' + i}}">Quantity</label>
<input type="number" formControlName="quantity" id="{{'quantity' + i}}" min="0">
<span> {{this.unitOfMeasure}}</span>
<label attr.for="{{'reasonCode' + i}}">Reason Code</label>
<select formControlName="reasonCode" id="{{'reasonCode' + i}}" placeholder="Reason Code" style="max-width: 100% !important" no-padding>
<option value="" disabled>Please select a reason code</option>
<option *ngFor="let reasonCode of this.reasonCodes">
{{reasonCode}}
</option>
</select>
<label attr.for="{{'operation' + i}}">Operation</label>
<select formControlName="operation" id="{{'operation' + i}}" placeholder="Operation" style="max-width: 100% !important" no-padding>
<option value="" disabled>Please select an operation</option>
<option *ngFor="let op of operList">
{{op.operString}}
</option>
</select>
<label>Action</label>
<button class="btn btn-primary btn-lg" type="button" (click)="removeItem(index)">Remove</button>
</div>
</div>