Automatically selecting the country phone code based on the country dropdown selection

When the country dropdown is changed, I want the corresponding phone code dropdown to be dynamically loaded.

  <div class="row">
    <div class="col-sm-8 col-md-7 col-lg-6 col-xl-5 pr-0">
      <div class="form-group py-2">
        <label for="country" class="font-weight-bold"><span class="text-danger">*</span>{{ 'Country' | translate }}</label>
        <select name="country" id="country" class="form-control" [(ngModel)]="collaboration.countryCode" required
                #country="ngModel">
          <option *ngFor="let countryCode of countryCodes" [value]="countryCode">{{countries[countryCode]}}</option>
        </select>
        <div class="invalid-feedback"
             [style.display]="country.hasError('required') && (country.dirty || createContactSubmitted) ? 'block' : 'none'">
          {{ 'reqFieldDesc' | translate }}
        </div>
      </div>
    </div>
    <div class="col-sm-8 col-md-7 col-lg-6 col-xl-5 pr-0">
      <div class="form-group py-2">
        <label for="validatePhone" class="font-weight-bold"><span class="text-danger">*</span>{{ 'PhoneNumber' | translate }}</label>
        <div class="input-group">
          <input type="tel" name="validatePhone" id="validatePhone" class="form-control"
                 [ngClass]="{'is-invalid': validatePhone.invalid && (validatePhone.dirty || createContactSubmitted)}"
                 [(ngModel)]="collaboration.validatePhoneNumber" ng2TelInput
                 [ng2TelInputOptions]="{initialCountry: 'us', preferredCountries: ['us', 'us']}" required
                 #validatePhone="ngModel" />
        </div>
        <div class="invalid-feedback"
             [style.display]="validatePhone.hasError('required') && (validatePhone.dirty || createContactSubmitted) ? 'block' : 'none'">
          {{ 'reqFieldDesc' | translate }}
        </div>
      </div>
    </div>
  </div>

I have initially set it to 'US' by default in the ng2TelInputOptions, but I intend for it to change based on the selected country in the dropdown.

[ng2TelInputOptions]="{initialCountry: 'us', preferredCountries: ['us', 'us']}" required

The desired output can be viewed here.

Answer №1

One option could be to utilize the setCountry() method, although I cannot guarantee its effectiveness. Since you are using a reference variable named "validatePhone", you might consider incorporating validatePhone.setCountry($event) in your .html file.

<select name="country" ... [ngModel]="collaboration.countryCode" 
    (ngModelChange)="collaboration.countryCode=$event;validatePhone.setCountry($event)">
          ...
</select>
<input type="tel" ... #validatePhone="ngModel" />

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

Error in HTML5 video: Unable to access property '0' as it is undefined

I am trying to create a simple block displaying an HTML5 video tag. I want the ability to play different videos along with their titles from a JSON file by using previous and next buttons. Clicking the next button should play the next video, and the same g ...

Incorporating JavaScript and Alpine.js to Monitor and Log Changes in Input Range Values

I have developed a basic app that logs the input range value to the console when the range input changes. Interestingly, it works flawlessly when I slide the slider left and right with my cursor. However, when I programmatically change the value using Ja ...

Angular's detectChanges function does not trigger the ngDoCheck method

When I run cdr.detectChanges() in a nested child component (Child1) which has a parent and another nested child component (Child2), only ngDoCheck is invoked in Child2. Why doesn't it invoke DoCheck in the current component (Child1) as well? How can I ...

Using JQuery to specify an attribute as "required" along with a value does not function as expected

Something seems off with this: $("#elementId").attr("required", "true"); In Chrome and Firefox, the DOM either displays required as the attribute (with no value) or required="" (empty value). Interestingly, it doesn't make a difference what value w ...

The click event is activated following the :active selector being triggered

My Angular application features a button with a slight animation - it moves down by a few pixels when clicked on: &:active { margin: 15px 0 0 0; } The button also has a (click)="myFunction()" event listener attached to it. A common issue arises w ...

One try-catch block in C# handling various classes for distinct JSON messages

I have four distinct classes designated for handling different JSON messages. These messages are always received simultaneously and need to be processed together. All of this is done in a single try-catch block, where I use deserialization to locate the a ...

Curved base of the main banner image

Struggling to achieve the perfect curve at the bottom of my hero image. Any suggestions on how to accomplish this would be greatly appreciated. I am aiming for something like this: https://i.stack.imgur.com/Emxfc.png body { margin: 0; background: lig ...

Eliminating the impact of a CSS selector

I have a complex mark-up structure with multiple CSS classes associated: classA, classB, classC, classD. These classes are used for both styling via CSS and event binding using jQuery selectors. The Challenge: I need the jQuery events to be functional whi ...

What is the best way to find the average time in Typescript?

I am dealing with an object that contains the following properties: numberOfReturns: number = 0; returns_explanations: string [] = []; departure_time: string = ''; arrival_time: string = ''; The departure_time property hold ...

What is the best way to divide percentages accurately in Angular?

I am currently working on splitting percentages dynamically with Angular. For example, if txtBox1 has 75%, I want to split the remaining 25% between txt2 and txt3. If I change txt1 to 50%, then I want txt2 and txt3 each to receive 25%. The values may vary, ...

Controller is not being triggered by Ajax method when there is a decimal value

I am currently working on implementing a time registration feature in my web application. Users can select the project they worked on and enter the number of hours spent on that project. Everything is functioning properly until users start adding half-hou ...

Switching ng-loading from a different component

I am currently utilizing ngx-loading and I would like to have the ability to control its visibility from child components. This is my current setup: Main Component import { Component, Injectable } from '@angular/core'; @Injectable() export cla ...

Having trouble displaying the Order List in Tailwind CSS and Next.js?

I am having trouble displaying an ordered list on my page. I have tried using the <ol> tag, but for some reason the numbers are not showing up. Even when I switch to the <ul> tag, it's still not working properly. Take a look at this scree ...

Angular Ahead-of-Time (AOT) compilation causes multiple route definitions to be

Having a bit of trouble configuring ahead-of-time compilation for my lazy-loaded Angular app. The lazy-loaded routes are specified in the app.routes.ts file, which is imported by app.module.ts. Running ngc results in the content of app.routes.ts being mer ...

Initial values are not retained for nested form components upon submission

In an attempt to incorporate nested form components in Angular using reactive forms and ControlValueAccessors, I have been following a helpful guide available at the following link: While most of my implementation is working correctly, I am encountering o ...

A TypeScript class utilizing a static variable with the singleton design pattern

I have a query regarding the most effective way to code this scenario: Within a class, I require a static variable that is accessible throughout the entire project: connection Singleton without namespace: class Broker { static connection: Connection = u ...

What is the most effective way to transmit a conditional operator via a TypeScript boolean field?

Currently, as part of my transition to typescript, I am working on incorporating a conditional operator into the table component provided by Ant Design. const paginationLogic = props.data.length <= 10 ? false : true return ( <> ...

What is the best way to update a canvas chart when the side menu is hidden?

I am facing an issue with the layout of my webpage, which includes a left side menu and a canvas chart. The left side menu occupies the first 155 pixels of the width, leaving the rest for the canvas chart set to a width of 100%. However, when I close the ...

Tips for integrating jsPDF with Angular 2

Encountering Error: jsPDF is not defined, while implementing the code below: import { Component, OnInit, Inject } from '@angular/core'; import 'jspdf'; declare let jsPDF; @Component({ .... providers: [ { provide: 'Window&a ...

Insert HTML content into an iframe with a callback function

We are receiving information from the backend server and need to transfer it to an iframe. In order to accurately set the height of the iframe to match the content, we must wait for the content to be loaded into the iframe. However, this process may not ha ...