如何在 Angular 中为 ngbDropdownMenu 添加验证?

How to add validation to ngbDropdownMenu in Angular?

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

<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>

我很难为此下拉列表添加简单的验证。如果在按下提交按钮后没有选择任何选项,我想显示一个错误。在 angular 上尝试了各种验证示例,但其中 none 似乎可以使用这种下拉列表(没有 <input> 等)

也试过类似的东西,但我认为它离正常工作还很远。

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

我已经设法自己创建了解决方案。我在提交之前做了这个,我的组件会检查 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>

component.ts

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

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