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:
(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.
@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?
Have you tried a ternary operator?
(keydown.enter)="!validate.invalid ? modal.close() : whatever you want in case of false condition"