Search code examples
angularng-bootstrapangular-validation

Angular: Template driven form field validation in ngBootstrap modal dialog


I have template driven form validation inside of an ngBootstrap dialog like this:

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

It works (almost) perfectly. BUT, as you can see, I use (keydown.enter) event handler on the input element. And it will still trigger the close method of the modal dialog, even though the textbox content might be invalid.

I tried the following without success:

  1. (keydown.enter)="if(!validate.invalid) modal.close();". It gives an error "Invalid token if". Obviously you cannot use if conditions in those event handler strings
  2. In the code that is being called upon modal dialog close, I tried to use ViewChild/ElementRef to get a hold on the element and check its validation state:

.

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

What can I do to prevent either keydown.enter from firing OR check the validation state of the field inside of my code?


Solution

  • Have you tried a ternary operator?

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