【问题标题】:Update value in select depending from other field in Angular 8根据Angular 8中的其他字段更新选择中的值
【发布时间】:2020-02-28 07:03:26
【问题描述】:

我正在尝试在 Angular 8 中更新 select 中的值。 我发现我可以使用:

$('#selectSeccion').val("SeccionOption");

这个选择是下一个:

<select name="seccion" class="form-control" id = "selectSeccion">
   <option *ngFor="let seccion of seccion" [ngValue]="seccion">{{seccion.seccion}}</option>
</select>

当我将 select 与 Angular 一起使用时,jQuery 代码不起作用,仅当 select 是正常的 html 时才起作用,例如下一个:

<select class="form-control" id = "prueba">
    <option value = ""></option>
    <option value = "other">other</option>
</select>

如何更新“ng”选择的值?

【问题讨论】:

  • 这能回答你的问题吗? Binding select element to object in Angular
  • 不要为此使用 jquery。通读文档或跟随英雄之旅教程,以便您更好地了解 Angular 的基础知识。
  • @Igor 我不是使用 Angular 的专家,可能绑定是答案,但是,您指出的答案不是更新选择,它会根据选择的更改更新值,但选择已更新手动,谢谢

标签: javascript jquery html angular typescript


【解决方案1】:

我不建议将 jQuery 与 Angular 一起使用。 你可以在这里阅读更多信息:http://www.learnangularjs.net/using-jquery-with-angular.php

最简单的方法

component.html:

<select [(ngModel)]="selectModel" (change)="selectionChange()">
    <option [value]="seccion" *ngFor="let seccion of seccions"> {{seccion}}</option>
</select>

component.ts:

selectionChange() {
    console.log(this.selectModel)
}

更改 selectModel 参数也会触发 select 更改。

【讨论】:

  • select 中的值是从另一个地方更新的,当(wheel)方法检测到另一个字段中的更改时我必须更新,因此我无法在(更改)中执行此操作。它应该以以下方式工作:我最初手动选择一个选项,我滚动我的主要选项(它删除了选择中的值),当我向后滚动时,我希望在第一次滚动之前看到我在选择中手动选择的选项.当我滚动主选项时,选择中的值应该出现和消失。谢谢!
  • 可以绑定一个改变selectModel参数的wheel事件
【解决方案2】:

根据之前的建议,我可以使用 Angular 进行更新,顺便说一句,这始终是最好的方法。没有 jQuery。我必须将我的选择更改为下一个

<select name="seccion" class="form-control" id = "selectSeccion" [(ngModel)]="value" #ctrl="ngModel">
    <option *ngFor="let seccion of seccion" >{{seccion.seccion}}</option>
</select>

在选择标签上添加它 > [(ngModel)]="value" #ctrl="ngModel" 并使用以下行更新 ts 文件: 值:字符串 = '';

updatingFunction(){ this.value = "SeccionUpdated"; }

如果有人需要,我会留下它

【讨论】:

    猜你喜欢
    • 2013-04-22
    • 1970-01-01
    • 2021-12-16
    • 2023-03-30
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    相关资源
    最近更新 更多