【问题标题】:How to update a multi select options from component如何从组件更新多选选项
【发布时间】: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


【解决方案1】:

我找到了答案,我需要使用扩展运算符强制它检测变化:

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);
        this.recipe.mainIngredients = [...this.recipe.mainIngredients];
    }
}

【讨论】:

    【解决方案2】:

    这在 p-multiselect 的情况下不起作用。

    模板:

    <p-multiSelect class="pull-down" id="checkedSecMail" dropdownIcon="pi pi-caret-down" [options]="req.secEmail"
                  [(ngModel)]="req.selectedSecMail" >
                  </p-multiSelect>
    

    ts:

     selectAllMailId($event,data){
          let rowData =  this.tempRecipients.filter(elem => elem.xyz == data.xyz);
          rowData[0].secEmail.map((secmails=> rowData[0].selectedSecMail.push(secmails.label)));
        }
    

    上述方法是在单击复选框时调用的。 并且正在检查多选复选框,但未显示选中的值

    【讨论】:

      猜你喜欢
      • 2012-02-19
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多