Tips for updating dropdown value from a child component in Angular version 8

I've been attempting to update the dropdown value from a child component in Angular 8, but I'm unsure of how to do it. If anyone has a solution, please help me out.

When I click on the France button, I want the dropdown value to be set to France.
If I click on the Germany button, I want the dropdown value to be set to Germany.
If I click on the Italy button, I want the dropdown value to be set to Italy.

app.component:

<select name="city" class="rounded-inputs20 select-select col-md-3" (change)="onChange($event.target.value)">
  <option *ngFor="let country of countries"  [value]="country.id">{{country.name}}</option>
</select>

body.component:

<button (click)="changeVal('France')">France</button>

<button (click)="changeVal('Germany')">Germany</button>

<button (click)="changeVal('Italy')">Italy</button>

Demo::https://stackblitz.com/edit/angular-dropdown-geishz?file=app%2Fapp.component.html

Answer №1

To transfer data from the body component to the app component, you must implement event binding using Output() and EventEmitter().

The necessary modifications should be made in the following files:

body.component.ts:

import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-body',
  templateUrl: './body.component.html',
  styleUrls: ['./body.component.css']
})
export class BodyComponent implements OnInit {
  
  @Output() valueChange = new EventEmitter()

  constructor() { }

  ngOnInit() {
  }

  changeVal(val){
    this.valueChange.emit(val);
  }

}

Add [(ngModel)]='selectedCountry' in the app component HTML to monitor dropdown changes as shown below,

app.component.html:

<p>
    App Component:
</p>

<select name="selectedCountry"  [(ngModel)]='selectedCountry' class="rounded-inputs20 select-select col-md-3" (change)="onChange($event.target.value)">
  <option *ngFor="let country of countries; let i = index" [value]="country.id"> 
    {{country.name}}</option>
</select>


<app-body (valueChange)="getValueChange($event)"></app-body>

In the code above,

(valueChange)="getValueChange($event)"
is where you retrieve the data from the clicked button.

Subsequently, in the app component TypeScript file, you can create a function to handle the button click changes from the body component and update the dropdown selection by assigning the value of

this.selectedCountry = selectedOption.id
,

  getValueChange(val) {
    const selectedOption = this.countries.find(x => x.name == val);
    this.selectedCountry = selectedOption.id;
    this.onChange(selectedOption);
  }

app.component.ts:

import { Component, OnInit  } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  name = 'Angular 5';

  cities = {};

  countries = [{
    id: 1, name: 'France' 
  },
  {
    id: 2, name: 'Germany' 
  },
  {
    id: 3, name: 'Italy' 
  },
  ];

  selectedCountry: any = this.countries[0].id;

  ngOnInit() {
    this.cities = this.countries.filter(x => x.id == 1);
  }

  onChange(deviceValue) {
    this.cities = this.countries.filter(x => x.id == deviceValue);
    console.log('onchange ', deviceValue)
  }

  getValueChange(val) {
    const selectedOption = this.countries.find(x => x.name == val);
    this.selectedCountry = selectedOption.id;
    this.onChange(selectedOption);
  }

}

Forked Stackblitz:

https://stackblitz.com/edit/angular-dropdown-65tfxg

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

Pause and be patient while in the function that delivers an observable

I have a function that loads user details and returns an observable. This function is called from multiple places, but I want to prevent redundant calls by waiting until the result is loaded after the first call. Can anyone suggest how this can be accompli ...

Unknown type encountered when using v-for with Vue3 item

I'm currently going through a Laravel bootcamp and following along with the tutorial. However, I encountered an error when trying to display the model with VueJS using v-for loop. Here is my code: type ChirpModel = { id: number, message: string, ...

Achieving a Subset Using Functional Programming

Looking for suggestions on implementing a function that takes an array A containing n elements and a number k as input. The function should return an array consisting of all subsets of size k from A, with each subset represented as an array. Please define ...

While the file does exist in the current directory, the `readFileSync` function is unable to locate

For my latest SvelteKit project, I was developing a Joke API using Bun as the runtime and TypeScript as the programming language. The goal of this API was to fetch one random dad joke from a text file that contained 363 jokes. Everything was going smoothly ...

What could be causing the module to break when my Angular service, which includes the httpClient, is added in the constructor?

After creating a backend RESTful API, I encountered difficulties while trying to access it. To address this issue, I developed a database-connection.service specifically for making POST requests. However, I am facing challenges in implementing this solut ...

Implement a loading spinner for autocompletion by utilizing an array as data source instead of relying on an

If you're interested in implementing autocomplete using an array instead of an in-memory web API, check out this thread for an example: Here's the updated search function in autocomplete.service.ts: search(filter: {name: string} = {name: '& ...

Is there a way to detect changes in a Service variable within an Angular component?

One of my components contains a button that activates the showSummary() function when clicked, which then calls a service named Appraisal-summary.service.ts that includes a method called calc(). showSummary(appraisal) { this.summaryService.calc(appraisal ...

What is the best approach to implementing self-referencing type validation in TypeScript?

I am working on creating a specific type that guarantees all fields listed in the requiredFields array are included in the defaults object. The goal is to have defaults trigger type errors if any of the names from requiredFields are missing, and if the va ...

Ways to tally selected checkboxes in Angular 7?

I'm struggling to count the checked checkboxes on my form that reads data from an array. I have tried a few methods, but nothing seems to work. Since this is new to me and I am not familiar with how it works, could someone please provide guidance? I a ...

I am seeking to modify the CSS of the parent component upon the loading of the child component in Angular

In my Angular blog, I have a root component with a navigation bar containing router links to create a single-page application. My goal is to darken the background around the link when the child component loads. Currently, the link highlights only when pres ...

Any class that utilizes the interface `IGeneratable` must include an `IGeneratorConstructor<T>` where `T` represents the class implementing the `IGeneratable` interface

My goal is to enforce the requirement that any class implementing the IGeneratable interface must also provide a IGeneratorConstructor<T>, where T represents the class implementing IGeneratable. Is this achievable in TypeScript (specifically version ...

Choosing to overload the plainToClass function may result in a type error

I've been tasked with compiling an angular project that contains mostly code written by someone else. Although the example below compiles successfully on one machine, it throws an error on different machines. import { plainToClass } from 'class ...

Using Regex to replace special characters in TypeScript

I need assistance in removing the characters "?" and "/" from my inner HTML string. Can you guide me on how to achieve this using regex? For example, I would like to replace "?" with a space in the following content. "Hello?How are you?<a href="http:/ ...

Make TypeScript parameter optional if it is not supplied

I am working with an interface that defines scenes and their parameters: export interface IScene<R extends string> { path: R; params?: SceneParams; } The SceneParams interface looks like this: export interface SceneParams { [key: string]: s ...

Is it possible to devise a universal click handler in TypeScript that will consistently execute after all other click handlers?

In my ReactJS based application written in TypeScript, we have implemented various click handlers. Different teams contribute to the application and can add their own handlers as well. The challenge we face is ensuring that a specific global click handler ...

Enforcing uniform data types in nested objects in TypeScript

Currently, I am in need of generating a list of constants. For instance, const Days = { YESTERDAY: -1, TODAY: 0, TOMORROW: 1, } I am looking for a method to restrict the types of all properties within Days. In other words, if I attempt to add a pr ...

Identify potential interference with Sentry.captureMessage(...) or Sentry.captureException(...) functions within a JavaScript application, such as being obstructed by an ad-blocking extension

Overview Our Javascript application uses Angular and TypeScript, with Sentry.io for error reporting. If an error occurs, a custom modal allows users to leave a message, which should be sent to Sentry when they click submit. Issue We have noticed that mes ...

Converting a TypeScript nested dictionary into a list of strings

I am currently working with a nested dictionary and my goal is to convert it into a list of strings. For example, the initial input looks like this: var group = { '5': { '1': { '1': [1, 2, 3], ...

There was an error reported by TypeScript stating that Nest.js is not considered a module

During the development of my project using Nest.js, I came across an error that I couldn't find a solution for. The issue arises when I try to export a function from one file and import it into a controller. Even though the function is exported correc ...

Unable to subscribe due to the return value being an AnonymousSubject rather than an Observable

I am facing an issue in Angular 4 where I am attempting to retrieve details from a specific user when clicking on the 'user link profile'. However, I am unable to subscribe to my function because the return value of switchMap is AnonymousSubject ...