Angular 2 - Enable service call only upon entering a valid email address

In my Angular 2 application, I have a child component that serves as a modal with fields for email, confirm email, and buttons to Send and Cancel. When I input an invalid email like "Henry" in both email and confirm email fields, the service call doesn't initiate due to the invalid input. However, when I provide a valid email address, I expect the service call to trigger. Essentially, the child component should emit the data to the parent allowing the service call to be made. This modal is simple, with just a Send button that triggers an email service call upon clicking. My objective is to execute the service call only when a valid email address is entered without utilizing any form-group validation, but relying solely on JavaScript regEx to validate the email expression.

HTML snippet:

 <md-input placeholder="Email" [(ngModel)]="email" name=""></md-input>
 <md-input placeholder="Confirm Email" [(ngModel)]="confirmEmail"name="">
</md-input>
<button (click)="sendEmail()">SEND</button>
<button>CANCEL</button>

In my TypeScript file (.ts):

export class appComponent{
@Input () emailData: {email:string,confirmEmail:string};
}

    validateEmail(email) {
            var re = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<<>()[\]\.,;:\s@\"]{2,})$/i;
            return re.test(email);
        }        
        private sendEmail() {                
            if(this.validateEmail(this.emailData)){        
                this.onEmailSend.emit(this.emailData);
            }
        }

During debugging, I noticed that while the service call does not proceed with an invalid email entry, it also fails to trigger even with a valid email address input, consequently resulting in the failure of sending the email. Can anyone pinpoint where I may be making errors?

Answer №1

Here is how you can define an output parameter for your component:

@Output() emailSent: EventEmitter<any> = new EventEmitter<any>();

Once you have defined the output parameter, you can emit an event like this:

this.emailSent.emit(this.emailData);

In your parent component, make sure to include the following method:

.
.
.
    emailSent(emailData)
    {
        console.log(emailData);
        // Add functionality to send an email
    }
.
.
.

Answer №2

If you're looking for a solution, consider the following:

<div class="alert-email">
        <label>Email</label>
            <input
                id="email"
                type="text"                
                #email="ngModel"
                [(ngModel)]="model.email"
                required
                pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$">

            <div class="md-errors-spacer" [hidden]="email.valid ||    email.untouched">
            <div  *ngIf="email.errors && email.errors.required">
                Email is required
            </div>
            <div  *ngIf="email.errors && email.errors.pattern">
                Email is invalid
            </div>
        </div>
    </div>

Don't forget that Angular 2 offers a convenient "email" validation tag to use within the input field.

<input type="email" id="contact-email" email>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Eslint is actively monitoring files specified in the eslintignore to ensure they meet the set

I am currently working on a TypeScript project that is bundled by Webpack. I want to integrate Eslint into the project, but I have encountered an issue where Eslint watches compiled files even if they are listed in the .eslintignore file. .eslintignore: . ...

In Angular, additional code blocks are executed following the subscription

I am facing an issue with my file upload function. After the file is uploaded, it returns the uploaded path which I then pass to a TinyURL function this.tinyUrl.shorten(data.url).subscribe(sUrl => { shortUrl=sUrl;});. However, there is a delay in receiv ...

Constructing objects in TypeScript is a breeze with its C#-ins

It seems like finding a simple solution for my task is proving to be quite challenging. I have a class that accepts 10 parameters, most of which are optional. To simplify things, I will illustrate my dilemma using just 3 parameters. I wish to be able to i ...

What is the reason behind this occurrence in TypeScript? (specifically union types)

I'm confused because I can't find a definite answer to this question: Consider the following type definition: type A = { prop2: string; prop1: string; } | { prop3: string; prop1: string; } This type includes one shared property ...

utilizing a simple input field with typescript

This situation is really getting on my nerves. I have a hidden input box that looks like this: <input type='hidden' id='iFrameDrivenImageValue' value='n/a'> Now, I am attempting to read its value from .ts file in order ...

IntelliJ IDEA mistakenly believes that the MouseEvent interface has already been declared

Can someone help explain the error TS2687:All declarations of 'x' must have identical modifiers.? I'm diving into the documentation for TypeScript to grasp the language better. The code snippet from the Function Parameter Bivariance section ...

Changing the data type of a column in an Excel file from XLSX to

I am currently working with the XLSX npm package and attempting to download a sample Excel file, add some data to it, and then upload it back. The fields in the file include MOBILE NUMBER, DATE, TIME, and NAME. When I upload the file, the values for the DA ...

Using [(ngModel)] in Angular does not capture changes made to input values by JavaScript

I have developed a custom input called formControl, which requires me to fetch and set its value using [(ngModel)]: import { Component, Injector, OnInit, forwardRef } from '@angular/core'; import { ControlValueAccessor, FormControl, NG_VALUE_ACCE ...

Passing a type as an argument in Typescript

How can I pass a type as a parameter in Typescript? type myType = {} const passingType = (t: Type) => { const x : t = {} } passingType(myType); I keep receiving TypeScript errors. 't' is referencing a value, but it is being used as a t ...

Navigate through Angular 2 array elements

I am facing an issue where I have an array and I need to display only a single object from the array at a time. The goal is to cycle through the array using a button, but I'm struggling to figure out how to display just one object at a time. You can s ...

Is there a way to conceal 'private' methods using JSDoc TypeScript declarations?

If we consider a scenario where there is a JavaScript class /** * @element my-element */ export class MyElement extends HTMLElement { publicMethod() {} /** @private */ privateMethod() {} } customElements.define('my-element', MyElement) ...

404 Error message encountered across all routes in a Node TypeScript Azure Function App - Resource not located

I keep encountering a 404 Not Found error on all routes while requesting my API. I am struggling to correctly write the code. Here's an example of my code: host.json: { "version": "2.0", "extensions": { & ...

Implement a function parameter as required or optional depending on another parameter in Typescript

Just diving into the world of TypeScript, I am attempting to implement type-checking for a function that has an optional third argument. Depending on another parameter, this third argument may or may not be utilized. I have designated it as optional but e ...

Typescript's dynamic React component and its conditional types

I am currently working on a dynamic React component and I am facing an issue with properly passing the correct propType based on the selected component. The error arises when using <SelectComponent {...props.props} /> because the props do not match t ...

Indexing types unexpectedly behaving and generating errors that were not anticipated

I find the code below quite strange... export class Collection { private data: {[k: string]: any} = {}; constructor () { // This part works fine this.data["hello"] = "hello"; // Unexpectedly works this.data[2] = 2; ...

Obtain data attributes using JQuery's click event handler

I'm facing an issue with a div structure setup as follows: <div class='bar'> <div class='contents'> <div class='element' data-big='join'>JOIN ME</div> <div class=& ...

Do I have to wait for promises to be resolved or does expect(...).toBe handle it automatically?

Testing with Protractor can be quite challenging and confusing, especially for those new to it. I currently have the following setup: `SomeTestFile.spec.ts` describe('A test: ', () => { beforeEach(() => { .... } it (& ...

Is there a way to update the text of a button when it is clicked?

Is there a way to dynamically change the text of a button when it is clicked and revert back to its original text when clicked again? I have attempted something along these lines, but I am unsure how to target the text since there isn't a property si ...

How can we implement a TypeScript interface that includes a constructor?

Currently, I am exploring an angular maps library that provides the following interface: export interface LatLng { constructor(lat: number, lng: number): void; lat(): number; lng(): number; } To utilize this interface and create an object for API ...

Is it possible to adjust the color of the iOS status bar using NativeScript, Angular 2, and TypeScript?

I recently came across this npm package called NativeScript Status Bar, available at the following link: https://www.npmjs.com/package/nativescript-statusbar However, I'm facing an issue because I cannot use a Page element as I am working with Angul ...