Reputation: 13216
I have an on screen form on which I need to asses the users entry in real-time to make sure that the pageName
they type in doesn't exist in the navbarMenuOptions
array. If it does, I want to toggle the stage of displayName
and displaySaveButton
. However, I am seeing a strange error wherein the keyup event doesn't fire. How can fix it?
Typescript
pageName: string;
displayError: boolean = false;
disableSaveButton: boolean = false;
navbarMenuOptions = ['Home', 'About', 'Features', 'Contact'];
validatePageName() {
if (!this.pageName) {
this.displayError = false;
this.disableSaveButton = true;
} else {
for(let i = 0; i < this.navbarMenuOptions.length; i++) {
if(this.pageName.toLowerCase() === this.navbarMenuOptions[i].toLowerCase()) {
this.displayError = true;
this.disableSaveButton = true;
} else {
this.displayError = false;
this.disableSaveButton = false;
}
}
}
}
HTML
<div class="modal-body">
<div class="alert alert-danger" role="alert" *ngIf="displayError">
A page with this name already exists.
</div>
Please enter a name for your new page.
<div class="form-group">
<label for="pageName"></label><input class="form-control" id="pageName" type="text" [(ngModel)]="pageName" (keyup)="validatePageName()">
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" [disabled]="disableSaveButton">Save</button>
<button (click)="onCloseButtonClick()" class="btn btn-secondary" type="button">Cancel</button>
</div>
Upvotes: 1
Views: 251
Reputation: 26460
Try with the following code (stackblitz example here):
validatePageName() {
if (!this.pageName || this.pageName.trim() == '') {
this.displayError = false;
this.disableSaveButton = true;
} else {
for(let i = 0; i < this.navbarMenuOptions.length; i++) {
if(this.pageName.toLowerCase() === this.navbarMenuOptions[i].toLowerCase()) {
this.displayError = true;
this.disableSaveButton = true;
break;
} else {
this.displayError = false;
this.disableSaveButton = false;
}
}
}
}
}
I'm guessing you are adding something like a space and expecting that it will disable.
I also added a break to make your error message work as the for loop will not work for true otherwise.
Upvotes: 1