Error message not shown by ng2-intl-input for invalid phone number

I'm currently working on implementing a validation rule for phone numbers in the form I'm designing. I've decided to utilize the ng2-tel-input library, even though my form is built using Angular 6.

However, I've encountered an issue where I am unable to display an error message when the phone number input is invalid.

Below is the snippet of my HTML code:

<input  class="form-control phoneField" 
                ng2TelInput 
                (hasError)="hasError($event)"
                (intlTelInputObject)="telInputObject($event)"
                type="text" pattern="^[\s0-9]*$" [required]="emailReq ? false : 
                !null" [(ngModel)]="phoneReq"
                name="phone" #phone="ngModel" phoneValidator style="width: 100% 
                !important">

Typescript code section

import * as ngTelInput from 'ng2-tel-input';
import 'intl-tel-input';
import 'intl-tel-input/build/js/utils';

export class  phoneValidator {
@Input('ng2TelInputOptions') ng2TelInputOptions: any;
@Output('hasError') hasError: EventEmitter<boolean> = new EventEmitter();
@Output('ng2TelOutput') ng2TelOutput: EventEmitter<any> = new EventEmitter();
@Output('intlTelInputObject') intlTelInputObject: EventEmitter<any> = new 
EventEmitter();    ngTelInput: any;

constructor (private el: ElementRef) {}
@HostListener('blur') onBlur() {
    let isInputValid:boolean = this.isInputValid();
    if (isInputValid) {
        let telOutput = this.ngTelInput.intlTelInput("getNumber");
        this.hasError.emit(isInputValid);
        this.ng2TelOutput.emit(telOutput);
    } else 
    {
        this.hasError.emit(isInputValid);
    }
}

isInputValid(): boolean {
    return this.ngTelInput.intlTelInput('isValidNumber') ? true : false;
}
}

As a newcomer to Angular, I am struggling to understand why it is not functioning correctly.

I attempted to test the hasError function with the following code:

   hasError(obj) {
        console.log('hasError: ', obj);
    }

It seems to be working fine, displaying 'true' for valid phone numbers and 'false' for invalid ones. However, the form does not detect an invalid number or show an error message accordingly.

If anyone can provide some guidance on this issue, I would greatly appreciate it.

Answer №1

After some digging, I finally uncovered the solution that may be useful to others:

In Typescript :

  hasError: boolean;
 onError(obj) {
        this.hasError = obj;
        console.log('hasError: ', obj);
    }

HTML :

 <input  class="form-control phoneField" 
                ng2TelInput 
                (hasError)="onError($event)"
                (intlTelInputObject)="telInputObject($event)"
                type="text" pattern="^[\s0-9]*$" [required]="emailReq ? false : !null" [(ngModel)]="phoneReq"
              name="phone" #phone="ngModel" style="width: 100% !important"></div>
              <span class="text-danger" *ngIf="!hasError">Please enter a valid phone number</span>

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

When using the `create-react-app` command with the `--typescript` flag, you may encounter an issue when attempting to compile namespaces with the `--

I started a project using npx create-react-app my-app-ts --typescript, then I added two new files, sw-build.js and sw.js in the src/ directory. The content of these files was taken from the discussion on Workbox guidelines at (Guidlines for Using Workbox) ...

Ways to address the Generic Object Injection Sink eslint error (security/detect-object-injection)

I am seeking a solution to resolve this issue without needing to deactivate eslint. Moreover, I am eager to comprehend the cause of the error. const getMappedCard = (cardName: CardName) => { const mappedCards = { Mastercard: <Mastercard /> ...

Ionic - interactive search feature

Is there a way to customize the behavior of a search bar so that it only reacts to taps or clicks without triggering the keyboard? I want to replicate the functionality of Google Maps where the user tap on the bar a new view or modal appears with a ...

Error: It is not possible to add the "providers" property as the object is not extendable within N

Ever since updating to the latest version of NGRX, I've been encountering an issue: users$= createEffect(() => this.actions$ .pipe( ofType(users.LOAD_USERS), tap((action: users.LoadUsersAction) => { action.item.name = ...

Create a collection of values and assign it to a form control in Ionic 2

How can I set default values for ion-select with multiple choices using a reactive form in Angular? FormA:FormGroup; this.FormA = this.formBuilder.group({ toppings:['',validators.required] }); <form [formGroup]="FormA"> <i ...

What is the best way to switch the CSS class of a single element with a click in Angular 2

When I receive data from an API, I am showcasing specific items for female and male age groups on a webpage using the code snippet below: <ng-container *ngFor="let event of day.availableEvents"> {{ event.name }} <br> <n ...

An interface in TypeScript that includes a method specifically designed to return exactly one type from a union of types

In my React function component, I have a generic setup where the type T extends ReactText or boolean, and the props include a method that returns a value of type T. import React, { FC, ReactText } from 'react'; interface Thing {} interface Prop ...

The ace.edit function is unable to locate the #javascript-editor div within the mat-tab

Having trouble integrating an ace editor with Angular material Error: ace.edit cannot locate the div #javascript-editor You can view my code on StackBlitz (check console for errors) app.component.html <mat-tab-group> <mat-tab label="Edito ...

Access uninitialized properties in Typescript post-compilation

I am currently in the process of creating a wrapper for socket.io. Coming from a strong object-oriented background, I aim to incorporate the idea of Models into my framework/wrapper. For those familiar with socket.io, you may know that data associated wit ...

Unable to store the array in the local storage

Background: In an attempt to implement a "Favourites List" feature where users can add favorite categories with heart icons on the home page, I encountered challenges. Despite searching for a logical flow on Google, I couldn't find a helpful solution. ...

Achieving automatic checkbox selection in Angular 6 through passing a value from one component to another

My page named second.html contains the following code: <div class="col-lg-4 col-md-4 col-sm-4"> <input type="checkbox" class="checkmark" name="nond" [checked]="r=='true'" (change)="nond($event, check)"> ...

Tips for managing sessions using Angular2 and Node.js

After extensive experience with express-session using mongodb as a session store, I now have the opportunity to work with Angular 2 on the frontend. I am curious about how to maintain session across both the frontend and server, considering they are operat ...

Tips for synchronizing the display of a table with the server response in an Angular application

* Project I am currently working on a project that involves retrieving player data from a json server and displaying it in a standard table format with a paginator. * Issue The challenge I'm facing is ensuring that the table data is loaded before th ...

Invoke the LazyQuery Hook within a Function

My GraphQL query implementation is as follows: const [loadUsers, { loading, data }] = useLazyQuery(LoadUsersQuery); When I utilize this code snippet in my project, the lazy query loadUsers functions properly and displays the results: return ( <d ...

What is the best way to share a parent component's input value with two child components using the Angular 4 Router module?

I am currently developing a simple Airbnb search feature. The project consists of 3 main components: SearchComponent, which contains the search form; ListingComponent, responsible for listing Airbnb rentals; and MapComponent, displaying markers on a Google ...

What is the best way to convert JSON into an Angular 7 object?

My challenge involves consuming a web API that provides the following data: { "FileStatuses": { "FileStatus": [ { "accessTime": 0, "blockSize": 0, "childrenNum": 13, "fileId": 16396, ...

Typescript struggling to load the hefty json file

Currently, I am attempting to load a JSON file within my program. Here's the code snippet that I have used: seed.d.ts: declare module "*.json" { const value: any; export default value; } dataset.ts: import * as data from "./my.json" ...

TypeScript generic type and potential absence of a value

Recently, I've been delving into Facebook's immutable library and exploring their TypeScript bindings. Consider this snippet of code: const list: User[] = ...; list.map(user => ...) The lambda parameter user correctly has the type of User. ...

Mapping an array based on specific conditions

When using my photo gallery app, I faced a challenge in mapping an array of images based on the user-selected album name. The current setup works perfectly for the 'Cambodia' album where all images are correctly logged in the console after mappin ...

A practical guide to troubleshooting typescript errors when exporting a map component

I encountered a typescript error when trying to export the map component with GoogleApiWrapper. It works fine when not wrapped in GoogleApiWrapper, but all my attempts to resolve the issue have failed. I would appreciate it if someone could review the code ...