我正在尝试构建一个"就地编辑"输入表单,以便在用户单击该字段时更改产品名称。我的问题是有问题的名称字段是使用 ngFor 循环打印出来的,我不知道会有多少,每个用户都会有所不同。 有没有办法动态更改名称字段,然后在表单中引用动态名称?我猜像这样的东西:nameField1,nameField2等,但使用循环从ngFor="let item of crudService.subscriptions.subscriptions
.html:
<tr *ngFor="let item of crudService.subscriptions.subscriptions; index as i">
<td>
<div *ngIf="!showEditName">
<div>
{{ item.productName }}
</div>
<div>
<button class="btn-sc btn-blac" (click)="editName(item.productName, i)">Edit</button>
</div>
</div>
<div class="col" *ngIf="showEditName">
<div class="md-form">
<input mdbInput mdbValidate type="text" class="form-control" [formControl]="nameField" />
<label for="editName">EditName</label>
</div>
<div>
<button class="btn-sc btn-blac" (click)="editName()">save</button>
<button class="btn-sc btn-blac" (click)="editName()">cancel</button>
</div>
</div>
</td>
</tr>
组件.ts:
import { FormControl } from "@angular/forms";
export class SubscriptionsComponent implements OnInit {
nameField = new FormControl("");
showEditName: boolean = false;
editName(itemName: string, subIndex: number) {
console.log(subIndex);
this.nameField.setValue(itemName);
this.showEditName = !this.showEditName;
}
}
我已经在Angular中看到了带有FormGroup构建器的formArray,但我发现很难理解,我不确定它是否是我需要的。
您可以使用索引值编辑名称,以便跟踪正在编辑的索引名称。因为只有通过索引值跟踪编辑输入的方法。
如果您想要 FormArray 示例,我可以为您提供以下解决方案是否适合您
<tr *ngFor="let item of crudService.subscriptions.subscriptions; index as i">
<td>
<div *ngIf="indexToEdit != i"> // make sure to track by index
<div>
{{ item.productName }}
</div>
<div>
<button class="btn-sc btn-blac" (click)="editName(item.productName, i)">Edit</button>
</div>
</div>
<div class="col" *ngIf="indexToEdit == i">
<div class="md-form">
<input mdbInput mdbValidate type="text" class="form-control" [formControl]="nameField" />
<label for="editName">EditName</label>
</div>
<div>
<button class="btn-sc btn-blac" (click)="editName()">save</button>
<button class="btn-sc btn-blac" (click)="editName()">cancel</button>
</div>
</div>
</td>
然后在 ts 文件中进行更改
import { FormControl } from "@angular/forms";
export class SubscriptionsComponent implements OnInit {
nameField = new FormControl("");
indexToEdit: number = null;
editName(itemName: string, subIndex: number) {
console.log(subIndex);
this.nameField.setValue(itemName);
this.indexToEdit = subIndex; // set index value and reset it after name edited
}
}