1

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?

1 Answer 1

1

Have you tried a ternary operator?

(keydown.enter)="!validate.invalid ? modal.close() : whatever you want in case of false condition"
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. It works, but because I don't need the "else" part, I used this !validate.invalid && modal.close($event). Then I do the $event.preventDefault() part inside of the modal.close code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.