Retrieving a complete array of countries from the mat-country-select package

I'm currently working with reactive forms in my Angular project and utilizing mat-country-select to display a list of countries in a select dropdown within my child FormComponent.

<mat-select-country class="full-width"
                            [formControl]="form.controls.country"
                            [required]="true"
                            appearance="outline"
                            [itemsLoadSize]="0"
                            [value]="DEFAULT_COUNTRY"
                            label="Choose country">
          
        </mat-select-country>

I am attempting to create a modal dialog window for updating a Player in the parent PlayerComponent, defined by the structure below:

export interface Player extends BaseResponse {
  lastName: string;
  firstName: string;
  dateOfBirth: Date;
  country: string;
  height: number;
  weight: number;
  position: string;
  jerseyNumber: number;
  teamName: string;
  teamId?: string | null;
  photoPath?: string | null;
}

Prior to opening the update dialog window in the PlayerComponent, I need to initialize and pass a form to my FormComponent.

export class PlayersComponent implements OnInit {
  countries: Country[] = COUNTRIES;
 playerActionsForm!: FormGroup<PlayerActionsForm>;

fillUpdatePlayerForm(player: Player) {
    this.playerActionsForm.controls.id.setValue(player.id);
    this.playerActionsForm.controls.firstName.setValue(player.firstName);
    this.playerActionsForm.controls.lastName.setValue(player.lastName);
    this.playerActionsForm.controls.birthDay.setValue(player.dateOfBirth);
    const country = this.countries.find(
      (country) => country.name === player.country,
    );
    this.playerActionsForm.controls.country.setValue(country ? country : null);
    this.playerActionsForm.controls.height.setValue(player.height);
    this.playerActionsForm.controls.weight.setValue(player.weight);
    this.selectTeams$
      .pipe(
        map((teams) => teams?.find((team) => team.id === player.teamId)),
        take(1),
        untilDestroyed(this),
      )
      .subscribe((team) => {
        this.playerActionsForm.controls.team.setValue(team ? team : null);
      });
    this.playerActionsForm.controls.jerseyNumber.setValue(player.jerseyNumber);
    this.playerActionsForm.controls.position.setValue(player.position);
    this.playerActionsForm.controls.experiences.setValue([]);
  }

  initializeActionsForm() {
    this.playerActionsForm = new FormGroup<PlayerActionsForm>({
      id: new FormControl(''),
      firstName: new FormControl('', [
        Validators.required,
        Validators.pattern(NAME_PATTERN),
      ]),
      lastName: new FormControl('', [
        Validators.required,
        Validators.pattern(NAME_PATTERN),
      ]),
      birthDay: new FormControl(null, [
        Validators.required,
        dateValidator(moment().subtract(18, 'years').toDate(), 'max'),
      ]),
      country: new FormControl(null, Validators.required),
      height: new FormControl(1.01, [
        Validators.required,
        Validators.min(1.01),
      ]),
      weight: new FormControl(50.01, [
        Validators.required,
        Validators.min(50.01),
      ]),
      team: new FormControl(null),
      position: new FormControl('', Validators.required),
      jerseyNumber: new FormControl(0, [
        Validators.required,
        Validators.min(0),
      ]),
      experiences: new FormArray<FormGroup<PlayerExperienceForm>>([]),
    });
  }

  ngOnInit(): void {
    this.initializeActionsForm();
    
  }

Currently, I am trying to utilize ViewChild to access the Input property of mat-country-select [Countries], however, it is not functioning as expected. As of now, I am using a predefined array named COUNTRIES which was manually created. Ideally, I am seeking a solution that can easily retrieve a specific country by name without the need for manually creating constants.

Answer №1

To import a list of countries, you can utilize the following steps:

Firstly, install the material-angular/countries package.

ng add @angular-material-extensions/select-country

In your component file, include the necessary imports:

import {Country,MatSelectCountryComponent,COUNTRIES_DB} 
                      from '@angular-material-extensions/select-country'; 

//or, for example, if you prefer the countries in Spanish
import {Country,MatSelectCountryComponent,COUNTRIES_DB_ES} 
               from '@angular-material-extensions/select-country'; 

Remember: If you wish to use these countries in your HTML template, declare a variable in your TypeScript file.

COUNTRIES=COUNTRIES_DB

When assigning a value to a FormControl that is different from what is displayed, consider using ngModel as shown below:

Simple example:

<mat-select-country [ngModel]="form.get('country')?.value"
                    (ngModelChange)="form.get('country')?.setValue($event)"
                    [ngModelOptions]={standalone:true}
</mat-select-country>

This code performs the same function as a formControl. The ngModel represents the formControl's value and invokes setValue when changed.

If you want to assign the entire object to the formControl, follow this approach:

<mat-select-country  [ngModel]="form.get('country')?.value?.name"
                    (ngModelChange)="setValue(form.get('country'),$event)"
                    [ngModelOptions]={standalone:true}
</mat-select-country>

setValue(control:AbstractControl,countryName:string)
{
  const country=COUNTRIES.find(x=>x.name==countryName)
  control.setValue(country)  
}

Note: You can use either patchValue or setValue methods to fill the formGroup. SetValue requires all properties, while patchValue does not.

const country = this.COUNTRIES.find(
  (country) => country.name === player.country,
);
this.playerActionsForm.setValue({...player,country:country})

Another option would be to simply assign the countryName to the formControl:

const country = this.COUNTRIES.find(
  (country) => country.name === player.country,
);
this.playerActionsFroms.setValue(player)
this.playerActionsForm.controls.country.setValue(country ? country.name : null);

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

Enhance your JavaScript with the addition of keyboard navigation feature

I am looking to enhance my image slider with pagination using a JavaScript function. Additionally, I want to incorporate keyboard arrow navigation (left and right) into the existing code. However, I have limited experience with JavaScript. Below is the cu ...

How can I pass the color hex value from the controller to the view without using quotation marks?

I'm having trouble sending a value and color pair using JSON. The color value needs to be returned to the JavaScript in the view as color: "#FFFFFF". I can send it to the view that way, but once the browser reads it, it turns into color: &quot;#FF ...

JQuery - Real-time computation and transformation within an interactive spreadsheet

I have a dynamic HTML table where rows can be added, and I am looking to read the value in Liters and convert it to US Gallons as the user enters the values. I want to take the input in Liters, convert it, and display it in the USG input field. View Dynam ...

The "Key" function from Object.keys does not yield true when compared to an identical string

Object.keys(data).forEach((key) => { bannerData[key] = data[key][0]; console.log(key); if (key == "timestamp") { labels.push(data[key]); console.log("wtf"); console.log(labels); ...

"Encountering a glitch in the Typescript/Node API where Express routes

Encountering a peculiar issue here - when attempting to import my router from an external file and add it as a route, I keep getting this unusual error where the string appears to be enclosed in double quotes. https://i.sstatic.net/nm9Wn.png ...

Extremely sluggish pagination in JQGrid following the implementation of a filter through the filter toolbar

I've encountered a problem while using jqGrid with LOAD ONCE and client-side paging. The addition of a filter toolbar has significantly slowed down the paging process after applying any kind of filter. $(gridElement).jqGrid({ postData: post, ...

Comparison between Browser Plugin and JavaScript for Rich Internet Applications

When it comes to the performance of my data intensive web application, which would be more efficient - a browser plug-in based RIA like SilverLight or a Java Script based RIA like ExtJS? For now, let's set aside considerations about plug-in availabil ...

.js script not being rendered within the ng-view

I am facing an issue with my index.html file which contains ng-view. I have included the necessary .js files in the index.html, but these scripts are not being applied to the injected view. index.html <!DOCTYPE html> <html class="no-js css-menub ...

Error: The system encountered an issue while trying to access an undefined property 'find'

I've been working on developing the backend for a wishlist feature, but I've encountered an issue with my code. (node:19677) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'find' of undefined Despite trying to redefi ...

Testing Angular components with Jasmine and subscribing to EventEmitters

I am currently testing a specific component in Angular, focusing on the eventEmitter located in the userService. import { Component, OnInit, OnDestroy } from '@angular/core'; import { RegisterUser } from 'src/app/classes/register-user'; ...

Tips for retrieving page source with selenium Remote Control

Looking to Develop a Basic Java Web Crawler. WebDriver driver = new HtmlUnitDriver(); driver.get("https://examplewebsite.com"); String pageSource=driver.getPageSource(); System.out.println(pageSource); The result is as follows: <!DOCTYPE html PUBLIC ...

Include a new row in the form that contains textareas using PHP

I'm trying to add a new row to my form, but I'm facing challenges. When I click the add button, nothing happens. If I change the tag to , then I am able to add a row, but it looks messy and doesn't seem correct to me. Here is my JavaScript ...

Koa fails to extract the 'body' from a fetch POST request

Recently, I've encountered an issue with my JavaScript code that sends POST data to my server. Even though the body data appears to be fine when printed out, Koa is not parsing the 'body' from the request using koa-bodyparser. This problem h ...

How can I retrieve the ngx-Summernote runtime value?

I am currently integrating ngx-Summernote into my Ionic 5 + Angular project. Is there a way to access the value using ngModel? I attempted: <div [ngxSummernote]="config" [ngxSummernoteView]="content"></div> The issue I&apo ...

What is the best way to incorporate GASP animation as a background in a React application?

Could someone help me implement this cool animation effect in my React application? https://codepen.io/celli/pen/xZgpvN <div id="container" /> <!-- React --> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.pr ...

Error: The function addToCart does not exist

Struggling to add products to the cart in React for the first time. Here's the code I'm working with: const data = { productData:[ { id: 1, image: "/assets/images/shop/product.jpeg", n ...

Error encountered with MobileFirst version 8 and Angular JS v1.5.3 integration using Bootstrap

I am encountering an issue with my Cordova application that integrates with MobileFirst Platform version 8, Ionic version 1.3.1, and AngularJS version 1.5.3. Upon bootstrapping AngularJS to connect the app to MobileFirst Platform, I encounter the following ...

Error: a is missing in the Google Maps configuration

I'm looking to integrate Google Maps into my program, but I've encountered an error stating that 'a is null' when using a variable in the Google Maps API. Below is my current implementation: //Creates a new center location for the goog ...

Creating a three-row CSS layout where the middle row aligns to the right side

I am working on developing a mobile device layout with 3 blocks. The first and third blocks contain text fields, while the second block is filled with a map. However, all of my blocks don't look good when they are too wide. The browser window can have ...

How can we incorporate dynamic HTML elements into a React JS application?

My code seems to be having an issue. I'm working on a registration form and trying to include an error message if the passwords entered do not match. For some reason, I am unable to dynamically add a para tag to my HTML. Any insights on why this could ...