【问题标题】:Not able to get Angular 2 dropdown current value in ngModel无法在 ngModel 中获取 Angular 2 下拉当前值
【发布时间】:2017-05-04 09:24:10
【问题描述】:

我想根据ngModel 的值获取选定值下拉列表:

<div class="form-group">
                  <div>
                  <label class="dropdown" for="profile">Profile <span style="color:red">*</span></label>
                  </div>
                  <div class="half">
                  <select class="form-control" name='profile' [(ngModel)]='users.profile._id' required>
                        <option *ngFor="let obj of profiles"  [value]="obj._id">{{obj.profile}}</option>
                  </select>
                  </div>
            </div>

【问题讨论】:

    标签: angular dropdown


    【解决方案1】:

    NgModel 指令用于下拉列表时,您应该始终使用NgValue 指令而不是value 用于列表项(选项):

    <select class="form-control" name='profile' [(ngModel)]='users.profile._id' required>
        <option *ngFor="let obj of profiles" [ngValue]="obj._id">
            {{obj.profile}}
        </option>
     </select>
    

    这应该可以解决您的问题。

    【讨论】:

    • 当值是字符串时,value 应该仍然可以,只有当值是其他类型时,ngValue 才需要 AFAIK。
    • @GünterZöchbauer 我不知道这一点。那么 OP 的问题是 users.profile._id 不匹配任何 obj._id 的。
    • 可能是因为它是一个数字,即使 JS 通常不介意将 1'1' 进行比较。我只是确定它应该适用于字符串值。
    • 谢谢我从你的谈话中得到答案:)
    【解决方案2】:

    感谢@Günter Zöchbauer 和@Stefan Svrkota

    我之前已将 this.users.profile='' 初始化为字符串,这是我的错误,它应该初始化为对象 this.users.profile={} ,其余代码正在运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-13
      • 2014-09-06
      • 2020-08-08
      • 1970-01-01
      • 2017-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多