【发布时间】:2018-08-16 10:55:49
【问题描述】:
我正在尝试从组件中更新多选。
我使用object属性作为选择的模型,选择Object属性的内容时会更新。
模板中的选择代码:
<div class="form-group">
<select multiple="" class="form-control" [(ngModel)]="recipe.mainIngredients" name="mainIngredients">
<option *ngFor="let ingredient of mainIngredients" value="{{ ingredient._id }}">{{ ingredient.title }}</option>
</select>
</div>
组件的代码:
autoSelectMainIngredients(ingredient: Ingredient) {
// gets the ingredient id to save in the object property (which is the ngmodel)
var mainIngredientId = this.mainIngredients.findObjectPropertyByAnotherProperty("title", ingredient.title, "_id");
if (mainIngredientId){
// select not updating
this.recipe.mainIngredients.push(mainIngredientId);
}
}
更新模型时未使用 id 更新多选。 我还能如何做到这一点? 谢谢。
编辑: 如果我在 ngOnInit 上更新 ngmodel:
this.recipe.mainIngredients.push("5a9e9e5a84d81edd7cb98e13");
其中“5a9e9e5a84d81edd7cb98e13”是一个有效值,它按预期工作,并且选择显示选择。
【问题讨论】:
-
你确定你有正确的 mainIngredientId 值并且它已被添加到 mainIngredients 数组吗?
-
是的,我将它记录到控制台。
-
select标签中的ngModel应该是选中选项的值。例如,如果选定选项的 id 为 5,则 select 中的 ngModel 将为 5。在这种情况下,您将数组 (recipe.mainIngredients) 与数字 (ingredient._id) 进行比较。要么删除 ngModel,要么将其设置为与成分相同类型的变量。_id。
-
这只是我在您的代码中看到的错误。仍然没有解释为什么你的选项没有更新:(
-
请看这个answer
标签: angular typescript