【问题标题】:ngModel directive not working with selected optionngModel 指令不适用于所选选项
【发布时间】:2017-05-04 16:48:51
【问题描述】:

我的 ionic 2 应用程序上有一个非常简单的表单。代码如下:

      <form #f="ngForm" (ngSubmit)="onBuscar(f)">
          <ion-item>

              <ion-label>Ano/Mês</ion-label>

              <ion-select
                  name="ano"
                  ngModel
                  required
                  okText="Confirmar"
                  cancelText="Cancelar"
                >
                <ion-option *ngFor="let ano of anos" value="{{ano}}" selected="{{ano==ano_atual}}">
                    {{ano}}
                </ion-option>
              </ion-select>

              <ion-select
                name="mes"
                ngModel
                required
                okText="Confirmar"
                cancelText="Cancelar"
              >
                <ion-option *ngFor="let mes of meses; let i = index" value="{{i + 1}}" selected="{{i==mes_atual}}">
                    {{mes}}
                </ion-option>
              </ion-select>

            </ion-item>

      </form>

问题是:当我输入“ngModel”指令时,我默认选择的选项出现了问题。没有它,它工作正常。但是,当提交表单时,我需要它在我的组件上获取我的表单值。任何想法如何解决它?

【问题讨论】:

    标签: angular typescript ionic2


    【解决方案1】:

    这不是 ngModel 应该被使用的方式。假设 ano_atual 是您要保存所选值的组件的属性,您可以这样做:

    <ion-select name="ano" [(ngModel)]="ano_atual" required okText="Confirmar" cancelText="Cancelar">
      <ion-option *ngFor="let ano of anos" value="{{ano}}">
        {{ano}}
      </ion-option>
    </ion-select>
    

    请注意,您不需要 selected 属性,因为 ngModel 指令将选择与 ano_atual 属性值相同的选项。

    【讨论】:

    • 谢谢,我就是这样做的,而且效果很好。但是,如果我不想将它绑定到我的组件中的属性,但仍想要选定的属性并想将值传递给我的组件函数怎么办?
    猜你喜欢
    • 2013-04-19
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    相关资源
    最近更新 更多