I am looking to dynamically print countries from an array in my code based on the selected option

I'm in need of some simple code assistance. I want to display a list of countries that correspond to a selected letter, but I'm struggling to do so dynamically at the moment. For example, if I select the letter A from a dropdown menu, I want the countries related to that letter to be displayed below the dropdown.

<select [(ngModel)]="selectedOption">
        <option *ngFor="let o of options">
          {{o.letter}}
        </option>
      </select>

<p *ngFor="let o of options">Countries are: {{ o.countries }}</p>

export class AppComponent {
  selectedOption: string;

  options = [
    { letter: "A", countries: ["Afghanistan", "Albania", "Argentina"] },
    { letter: "B", countries: ["Bangladesh", "Bahamas", "Bahrain"] }
  ]

}

If A is chosen, then Afghanistan, Albania... should be displayed. If B is chosen, then... If C is chosen, then... I also want to be able to expand the array in the future.

Answer №1

To simplify your code, consider using ngValue instead of relying on ngFor. Take a look at this post for more information. You can view a live example here.

Your updated code should look like this:

<select [(ngModel)]="selectedOption">
  <option *ngFor="let o of options" [ngValue]="o">
    {{o.letter}}
  </option>
</select>

<!-- Just to debug and display selected object -->
{{selectedOption | json}} 

<p>{{selectedOption.countries}}</p>

Answer №2

Give this a shot

<p *ngFor="let o of choices">
 <label *ngIf="o.letter === chosenOption">The list of countries is: {{ o.countries }}<label>
</p>

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

The routing functionality in an Angular Element seems to be malfunctioning when used in a separate Angular project. Instead of displaying the expected routes, only the "<router-outlet></router-outlet>" tags are visible on the website

The current situation: Our team is facing the challenge of integrating multiple angular frontend micro-services into a single application. To achieve this, we have chosen to use the Angular-Elements approach which resulted in a large JS-file when exportin ...

Adding shadows to a ShaderMaterial in three.js: A step-by-step guide

My current challenge involves using a customized shader to incorporate gradient colors onto a model. However, I have noticed that the shader lacks clarity when it comes to displaying shadows with well-defined edges (as shown in the first image). It seems t ...

Do these exports serve the same purpose?

Can someone help me understand why one export works while the other doesn't? I've tried to figure it out on my own but I'm stuck. Functioning Example const dataStore = new Vapi({ baseURL: 'http://domain.test/api', state: ...

Triggering the creation of an Algolia Index from Firestore operations like updates, deletions, and additions is causing significant delays

I'm currently developing an application with Algolia integration and Firebase compatibility. To utilize Algolia's features, I have incorporated the firebase extension from this link. This allows for real-time synchronization of data between Fire ...

Creating a progress bar for file uploads without using jQuery

We're currently seeking a way to implement a file upload progress bar feature without relying on ajax or jQuery. Unfortunately, we haven't come across any helpful tutorials through our Google searches. Below is the basic code snippet we have so ...

Achieving success in element-ui vuejs involves validating the state with the :error parameter

I recently developed an app using Laravel, Vuejs, and Element-ui. Within my form, I have utilized the "error" property to indicate that Laravel validation is in place. <el-form-item label="First Name" prop="firstname" :error="registerForm.errors.get(&a ...

Enable the entire button to be clickable without the need for JavaScript by utilizing a Bootstrap 5 button

Is there a way to make a button redirect when clicking anywhere on it, not just the text inside? Here is the button code utilizing Bootstrap 5: <button class="btn btn-rounded btn-primary" type="button">Placeholder Text</button& ...

What is the reason that modifying a textarea causes the AJAX loading of content to be interrupted?

I am currently developing a feature that allows users to quote comments on my website. When a user wants to reply to a specific comment, they can simply click on the "quote" button next to that comment. This action triggers a script that adds the quoted co ...

Difficulty encountered when combining create-react-app with typescript and immutable.js

After realizing that create-react-app now supports typescript, I encountered some issues while trying to transfer my current codebase from react-scripts-ts. Most of my classes are based on Record and cannot be constructed anymore due to errors like: Cannot ...

Ways to verify AJAX Response String when data format is specified as JSON

When using AJAX to retrieve JSON data from a webpage, it's essential to set the responseType to json. If the data processing is successful, a valid JSON string is returned, which works perfectly. However, if there's an error on the webpage, inst ...

The user model cannot be assigned to the parameter of type Document or null in a mongoose with Typescript environment

While working with Typescript, I encountered an error related to mongoose. The issue arises from the fact that mongoose expects a promise of a mongoose document (in this case, the user's document) or "null" to be resolved during a search operation. Ho ...

Custom input in Angular 2 rc.5: Form control is missing a value accessor for an unspecified name

My custom input component is designed as follows: import {Component, Provider, forwardRef} from "@angular/core"; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms"; const noop = () => {}; const CUSTOM_INPUT_CONT ...

Using Jquery to generate key value pairs from a form that is submitted dynamically

I'm still learning the ropes of jquery and struggling with a specific issue. I'm looking for a way to dynamically set key:value pairs in the code below based on form inputs that have variable values. The code works when I manually add the key:va ...

Could the "IonApp" class found in @ionic/angular (Ionic 4) be considered the updated version of the "App" class in ionic-angular (Ionic 3)?

I am currently in the process of upgrading an older Ionic app to Ionic 4. Previously, there were no issues before the migration I am working on a provider file helper.ts, and I have encountered a problem during the migration. Here is the output of ionic ...

Generating dynamic text in Angular based on certain conditions

I am still learning about Angular. Can someone please explain how to make text dynamic based on a count? For example, if the count is greater than 2, the text should be "Teams," and if it is less than or equal to 2, the text should be "Team." Here is what ...

Locate and eliminate all occurrences of "<br />" within a webpage using jQuery

I am currently working on a project using the Cargo Collective platform and I have noticed that it automatically includes unnecessary <br /> tags in the body of my document. Is there a way to use jQuery to scan for all instances of <br /> tags ...

Navigating through Angular2 notifications using router chaining

I am currently working on a simple application form where, upon submission, the user is redirected to another page. My goal is to display a success message when the submit button is clicked. The code snippet below functions as expected, but there is an is ...

Create a time of 00:19:59 using JavaScript

I am attempting to display a countdown timer that starts at 20 minutes in the format (00:20:00) using setInterval. Once the countdown is finished, it should display as (00:00:00), but I am having trouble achieving this. <body onload = "onloadFunc();" ...

Move images horizontally next to the height of an element

I am attempting to increase the top attribute in relation to the element it is currently adjacent to. The element should only scroll directly next to the other element and cease when it surpasses the height of that element. My Goal: I want the image to re ...

The never-ending loading problem at the bottom of the Firefox screen seems

I am facing an issue while trying to open something in Firefox using window.open(). The loading screen seems to never stop, and I cannot pinpoint the reason behind it. Any advice on how to resolve this would be greatly appreciated. View Screenshot: This ...