I am working on project using angular 8 in which i have implemented ng-2 tag input. In this tag-input i am trying to enter create chips using email id only.I need to create chip only if valid email is typed and either tab or space bar key is pressed. But the problem is chips are getting created before the logic of email validation is executed. sharing the code for better understanding component HTML <label class="csat-lable">Customer Email Id<span class="red-dot-mandt">*</span></label> <div class="gl-typeahead gl-typehead-customer-email-fix"> <tag-input class="customer_email_height-fix" formControlName="customer_email_id" [secondaryPlaceholder]="'Enter Customer Email Id'" [placeholder]="'Enter Customer Email Id'" [addOnPaste]="true" (keyup.tab)="onKeyDown($event)" (keyup.space)="onKeyDown($event)" id="customer_email_id" [separatorKeyCodes]="[32,9]" #cEmailInput > </tag-input> </div> component Ts emailChips: string[] = []; onKeyDown(event: KeyboardEvent) { debugger; const inputElement = event.target as HTMLInputElement; const email = inputElement.value.trim(); // Handle Spacebar (keyCode 32) if (event.key === ' ' || event.keyCode === 32) { if (email && this.isValidEmail(email)) { this.emailChips.push(email); // Add valid email to the array inputElement.value = ''; // Clear the input field after adding chip event.preventDefault(); // Prevent form submission or focus shift } else { alert('invalid email address'); console.error(`${email} is not a valid email.`); // Log invalid email attempts } } // Prevent 'Enter' key from submitting the form if (event.key === 'Enter' || event.keyCode === 13) { event.preventDefault(); } // Handle Tab key (keyCode 9) for chip creation if (event.key === 'Tab' || event.keyCode === 9) { if (email && this.isValidEmail(email)) { this.emailChips.push(email); // Add valid email to the array inputElement.value = ''; // Clear the input field after adding chip event.preventDefault(); // Prevent focus from moving to next element } else{ alert('invalid email address'); } } } isValidEmail(email: string): boolean { const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // Simple email validation regex return regex.test(email); } as you can see in the screenshot that chips got first created then alert message appears which is wrong as for invalid email should not get created.how to fix as i have tried everything but nothing works. any input/help will be highly appreciated. Thanks Continue reading...