【问题标题】:Angular: Template driven form field validation in ngBootstrap modal dialogAngular:ngBootstrap 模态对话框中的模板驱动表单字段验证
【发布时间】:2019-05-07 22:42:43
【问题描述】:

我在 ngBootstrap 对话框中进行了模板驱动的表单验证,如下所示:

<ng-template #content let-modal>
  <div class="modal-header">
     ...
  </div>
  <div class="modal-body">
    <form>
      <label for="newplaylistname">Name:</label>
      <input #validate="ngModel" name="newplaylistname" id="newplaylistname" pattern="^[A-Za-z0-9\s-_]+$" ngbAutofocus (keydown.enter)="$event.preventDefault();modal.close();" type="text" [(ngModel)]="newplaylistname"/><br/>
        <!-- Validator Message -->
        <div *ngIf="validate.invalid && (validate.dirty || validate.touched)"
            class="alert alert-danger">

          <div *ngIf="validate.errors.pattern">
            Der Name darf nur Buchstaben, Ziffern und Leerzeichen sowie _ und - enthalten.
          </div>

        </div>
    </form>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-default" (click)="modal.dismiss()">Abbrechen</button>
    <button type="button" class="btn btn-primary" (click)="modal.close()" [disabled]="validate.invalid">Anlegen</button>
  </div>
</ng-template>

它(几乎)完美地工作。但是,如您所见,我在输入元素上使用(keydown.enter) 事件处理程序。即使文本框内容可能无效,它仍然会触发模态对话框的关闭方法。

我尝试了以下方法但没有成功:

  1. (keydown.enter)="if(!validate.invalid) modal.close();"。它给出了一个错误“如果令牌无效”。显然,您不能在这些事件处理程序字符串中使用 if 条件
  2. 在模式对话框关闭时调用的代码中,我尝试使用 ViewChild/ElementRef 来获取元素并检查其验证状态:

.

 @ViewChild("validate") validateRef: ElementRef;
 ...
 if(!this.validateRef.nativeElement.invalid)
 // or if(!this.validateRef.invalid)
 // both give undefined already for this.validateRef

我可以做些什么来防止 keydown.enter 触发或检查我的代码中字段的验证状态?

【问题讨论】:

    标签: angular ng-bootstrap angular-validation


    【解决方案1】:

    你试过三元运算符吗?

    (keydown.enter)="!validate.invalid ? modal.close() : whatever you want in case of false condition"
    

    【讨论】:

    • 谢谢。它有效,但因为我不需要“else”部分,所以我使用了这个!validate.invalid &amp;&amp; modal.close($event)。然后我在 modal.close 代码中执行$event.preventDefault() 部分
    猜你喜欢
    • 1970-01-01
    • 2014-11-13
    • 2018-10-26
    • 2018-01-13
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    相关资源
    最近更新 更多