【问题标题】:How to add validation to ngbDropdownMenu in Angular?如何在 Angular 中向 ngbDropdownMenu 添加验证?
【发布时间】:2020-07-01 11:30:56
【问题描述】:

我有一个带有几个下拉列表的表单,如下所示:

<form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
    <button type="button" class="btn btn-outline-primary w-100 dropdown-toggle" id="operatorDropdown"
           ngbDropdownToggle>{{operator.name ? operator.name : 'Select your operator' | translate}}</button>
           <div ngbDropdownMenu aria-labelledby="dropdownExample" class="w-100 mb-3" #dropdownmenu >
           <button type="button" *ngFor="let option of operators" class="dropdown-item" (click)="operator = option"
                   [ngClass]="{'active':operator.name === option.name}">{{option.name}}</button>
           </div>
</form>

我很难在这个下拉列表中添加一个简单的验证。如果在按下提交按钮后没有选择任何选项,我想显示一个错误。尝试了有关角度的各种验证示例,但似乎没有一个适用于这种下拉列表(没有&lt;input&gt; 等)

也尝试过类似的方法,但我相信它远未正常工作。

<div *ngIf="f.controls.operatorDropdown?.errors">Error message goes here. </div>

【问题讨论】:

  • 基本上你只需要为operatorDropdown控件添加Validators.Required并在菜单项点击时设置控件值。能否请您提供 stackblitz,以便我可以帮助您完成它?
  • 感谢您的努力,我已经自己解决了,在下面评论了解决方案:)

标签: html angular typescript validation ng-bootstrap


【解决方案1】:

我自己设法创建了解决方案。我在提交之前做了这个,我的组件会检查operator.name 是否为undefined(未选中)。如果是,它将取消隐藏错误消息,如果不是,它将继续并提交表单。

还将验证添加到(click) 按钮事件,因此在显示错误后,如果用户选择运算符,它将验证operator.name 不再是undefined 并隐藏错误消息。

我将分享我的最终版本,欢迎评论。

component.html

<form name="form" #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
    <div ngbDropdown [className]="!isOperatorEmpty ? 'u-mw-300p u-mw-xs-100' : 'u-mw-300p u-mw-xs-100 is-invalid'">
  <button type="button" class="btn btn-outline-primary w-100 dropdown-toggle" id="operatorDropdown"
          ngbDropdownToggle>{{operator.name ? operator.name : 'Select your operator' | translate}}</button>
  <div ngbDropdownMenu aria-labelledby="dropdownExample" class="w-100 mb-3">
    <button type="button" *ngFor="let option of operators" class="dropdown-item" (click)="operator = option;validateOperatorDropdown()"
            [ngClass]="{'active':operator.name === option.name}">{{option.name}}</button>
  </div>
</div>
<div class="invalid-feedback u-mw-300p u-mw-xs-100" [hidden]="!isOperatorEmpty">{{"Please select operator." | translate}}</div>
</form>

组件.ts

  validateOperatorDropdown() {
    if (this.operator.name === undefined) {
      this.isOperatorEmpty = true;
    } else {
      this.isOperatorEmpty = false;
    }
  }

  onSubmit(f: FormsModule) {
    this.validateOperatorDropdown()
    if (!this.isOperatorEmpty) {
      //continue
    }
  }

【讨论】:

    猜你喜欢
    • 2019-07-11
    • 1970-01-01
    • 2016-04-06
    • 2020-01-10
    • 2019-06-29
    • 2021-03-11
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多