What is the process for emitting and receiving values in an Angular 2 component?

When I select a value from a dropdown, I want to pass it from the child component to the grandparent component. Depending on the selected option, I need to trigger a specific method in the theme config.

<select  (change)="changedvalue($event)"  class="selectionbox" [(ngModel)]="selectedValue" required>
            <option value="1">red</option>
            <option value="2">blue</option>
            <option value="3">green</option>
            <option value="4">Teaching</option>
            <option value="5">Marketing</option>
        </select>

changedvalue(event){
      console.log(this.selectedValue);
      this.formeService.testdata(this.selectedValue);
    }

FormeService.ts

import {Injectable, Component, Directive, EventEmitter, Output} from '@angular/core';
  @Injectable()
  export class FormeService {
    @Output() change = new EventEmitter<any>();
    testdata(value) {
      this.change.emit(value)
    }

Grand parent component.ts

  ngOnInit(): void {
    this.formeService.change.subscribe((value)=> {
      console.log(value);
      if (value === 1) {
        this.themeConfig.config();
      } else if (value === 2) {
        this.themeConfig.config2();
      }
    });
  }

Answer №1

If you want to keep track of select changes, you can easily do so without the need for a service. Check out this helpful tip on Stack Overflow: How can I get new selection in "select" in Angular 2?

For example, you just need to follow these steps:

    <select (change)="changedvalue($event.target.value)" class="selectionbox" [(ngModel)]="selectedValue" required>
  <option value="1">red</option>
  <option value="2">blue</option>
  <option value="3">green</option>
  <option value="4">Teaching</option>
  <option value="5">Marketing</option>
</select>

changedvalue(value){
      if (value === 1) {
        this.themeConfig.config();
      } else if (value === 2) {
        this.themeConfig.config2();
      }
    }

PS: Remember to import the FormsModule from @angular/forms in your module like this:

import { FormsModule } from '@angular/forms';

and add it to the imports list in your module :

@NgModule({
  imports: [
    FormsModule,
    // etc...

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

Modifying Array Values in Angular 7

I am currently dealing with a complex array where questions and their corresponding answers are retrieved from a service. Upon receiving the array, I aim to set the 'IsChecked' attribute of the answers to false. The snippet of code I have written ...

I am encountering difficulties while attempting to import Typescript files. Upon compiling them into Javascript, I am faced with errors in the web browser, specifically the issue of "exports is not defined"

When I run TodoAppUI.js:15, I get an error saying "Uncaught ReferenceError: exports is not defined" In all my classes, I use the export keyword. For example: export class mysclass { public constructor(){} } Even though I have the proper syntax for impo ...

Executing a function when a value changes in ng-selectize

I recently started using Angular and I found this useful library for select options - https://github.com/NicholasAzar/ng-selectize Although two-way binding is functional, I am facing difficulty in triggering a function when the select value changes. Take ...

Eliminate insignificant data in Highcharts stacked column charts

The image below shows the same data series. In the stacked column chart at the top of the image, small values appear to be missing (although they are present in the dataset), while they are visible in the area chart at the bottom. What could possibly be c ...

Parameters in Typescript decorators

Can someone help me understand the various parameters of a Typescript decorator? function myDecorator(target) { // do something with 'target' ... } In the given example, I am aware that 'target' represents the function/class to wh ...

How can I fetch external data before the canActivate guard is triggered in Angular2 CLI?

Currently, I have several http calls that need to be processed within the app component before the canActivate guard method is triggered. Here is how the routing is set up: { path: '', redirectTo: '/home', pathMatch: 'full' ...

What are the top techniques for designing with Angular 2 Material Design?

As a newcomer to angular 2 material design, I have noticed the primary, accent, and warn classes that apply specific colors to elements. Are these the only styling options available in Angular Material 2? Are there other classes that can be utilized for cu ...

Tips for addressing the error "Ensure each child in a list has a distinctive 'key' prop" in a React function using TypeScript

Encountered the following warning: Warning: Each child in a list should have a unique "key" prop. Inspect the render method of TabContext. Refer to https://reactjs.org/link/warning-keys for more details. in TabForGroupInList (at Product.tsx:148) ...

Learn how to retrieve data from a JSON server in Angular 8 and then sort that data in a table by utilizing checkboxes

Currently, I'm in the middle of an Angular project where I could use some assistance on how to filter data through checkboxes within a table. The setup involves a home component that displays data from a JSON server in a tabular format using a service ...

Bringing in Data with Angular

For my Angular projects, I attempted to utilize csv files in the following manner: import * as data1 from "./data.csv"; import * as data2 from "./data2.csv"; These files are situated in the same directory as the .ts file that I am trying to access them w ...

Tips for importing a .ts file into another .ts file within an Angular 5 application

I have a bunch of utility methods stored in a file called utils.ts that I want to reuse across multiple components. I'm not sure if it's even possible, and if it is, where should I place the import statement and what would be the correct syntax. ...

Ways to effectively utilize an interface incorporating props.children and other property varieties

Currently working on a project with Next.js and Typescript. In order to create a layout component, I defined the following interface: export interface AuxProps { children: React.ReactNode; pageTitle: 'string'; } The layout component code sn ...

Exclude attribute features from a Typescript interface

I need to exclude all functions from an interface interface Person { firstname: string; lastname: string; walk: () => void; speak: (phrase: string) => Promise<void> } type PersonWithoutFunctions = RemoveFunctions<Person> /* de ...

Steps to reset Pipe in Angular 4

Is there a way to reinitialize a Pipe in Angular 4? I currently have a component that utilizes a Pipe. The component renders once with some data that uses the Pipe. If the data changes, the Pipe will also need to change. What is the best method to rein ...

I'm interested in retrieving just the ID specifically when filtering in Angular

This is the filter I have in my service.components.ts this.pijatService .getById(this.id) .pipe(first()) .subscribe((x: any) => { this.form.patchValue(x); console.log(x); this.form.value.nomor_telepo ...

conditionally trigger one observable in rxjs before the other

I am in need of assistance or guidance regarding a challenge I am facing with rxjs that I cannot seem to resolve. In essence, my goal is to trigger an observable and complete it before the original one is triggered. Scenario: I am currently working on a ...

Angular 2 FileReader: A comprehensive guide

I have a situation where I need to upload an image in section X and pass the base 64 data of the uploaded image to section Y. But I am encountering some difficulties in section X HTML: <input type="file" id="hotspot" (change)="uploadHotSpot($event)"&g ...

Nest JS encountering an error due to an undefined property

Recently, my application was running smoothly until I attempted to fetch the documentation using Swagger. It seems like there might be a dependency issue causing it to stop working, but I can't pinpoint the root of the problem. An error message keeps ...

Can anyone provide guidance on how to define a generic constraint that guarantees the value types of a shared key in two different types are identical?

I am currently working on a function that copies fields from one object to another, and I have two main requirements: The key provided must be common between both objects. The value type corresponding to the given key should be the same in both objects. ...

What could be causing the parameter "id" to be undefined in Nest JS

Exploring the layout of the project directory, I am currently utilizing yarn berry for the monorepo setup with two distinct packages. The first package houses all the applications, while the second one contains shared libraries and modules. `- apps bff ...