所以在Angular2应用程序中我有一个名为'recipe.ingredients'的字符串数组,我有一个表单设置允许您编辑成分,添加和删除文本字段(和数组中的项目)的按钮.
<ul class="list-unstyled">
<div class="row" *ngFor="let ingredient of recipe.ingredients; let i=index">
<li>
<div class="col-xs-4">
<input
size="20"
type="text"
class="form-control"
[ngModel]="recipe.ingredients[i]"
#t
(blur)="recipe.ingredients[i]=t.value"
required>
</div>
<div class="btn-group col-xs-2" role="group">
<button
type="button"
class="btn btn-default btn-xs"
(click)="recipe.ingredients.splice(i,1)">-</button>
<button
type="button"
class="btn btn-default btn-xs"
(click)="recipe.ingredients.splice(i+1,0,'')">+</button>
</div>
</li>
</div>
</ul>
Run Code Online (Sandbox Code Playgroud)
你会注意到我没有用[(ngModel)]双向绑定到recipe.ingredients [i],那是因为我试过了,每次你输入一个字符时,文本框都会失去焦点.我认为这与*ngFor踩过数组有关.无论如何,目前这种解决方法很好,但现在我添加了一些功能,我需要两种数据绑定才能工作.知道如何重构这个以使其工作吗?