Show content based on dynamically selected dropdown in Angular

I am facing an issue with a dynamic select element in Angular. I am struggling to display the selected values on the view because I cannot seem to create a click event on the dropdown options or access the selected option via a click event on the <select> tag.

Below is the HTML code snippet:

<router-outlet></router-outlet>
<hr>
<div class="row">
  <div class="col-xs-12">
    <form [formGroup]="catSelection">
      <select 
      formControlName="transactionControl" 
      (change)="onDisplayCategory()">
    <option  [ngValue]="transactionCategory" *ngFor="let transactionCategory of transactionCategories">{{transactionCategory}}</option>
    </select>
    </form>
  </div>
<div></div>
</div>

And here is the TypeScript code:

import { Component, OnInit } from '@angular/core';
import { DataFetchingService } from '../shared/data-fetching.service';
import { Transaction } from '../shared/transaction.model';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-transactions',
  templateUrl: './transactions.component.html',
  styleUrls: ['./transactions.component.css']
})
export class TransactionsComponent implements OnInit {
  result: Transaction[]
  transactions: Transaction[]
  transactionCategories: Set<string>
  catSelection: FormGroup;

  constructor(private dfService: DataFetchingService) { }

  ngOnInit() {
    this.catSelection = new FormGroup({
      'transactionControl': new FormControl(null)})
    this.loadPosts()
  }

  loadPosts() {
    this.dfService.fetchData().subscribe(
      posts=>{
        this.transactions=posts;
        this.transactionCategories = new Set<string>(posts.map(p => p.category))
        console.log(this.transactionCategories)
        console.log(this.transactions)
      }
    )
  }

  onDisplayCategory() {
    console.log("change works")
  }
}

You can view the implementation on Stackblitz: https://stackblitz.com/edit/angular-6ni1pg

Answer №1

If you want to achieve this, Angular's two-way binding is the way to go.

To implement it, simply add [(ngModel)]="selectedCategory" to your select element. Then, in your TypeScript (ts) file, use selectedCategory as a variable to access the chosen option. You can then utilize this variable when an option is selected.

onDisplayCategory() {
  console.log("change works");
  console.log(this.selectedCategory)
}

I have made some modifications to your example, check it out: https://stackblitz.com/edit/angular-yx9jhq

Answer №2

To retrieve the values of the dropdown menu you have chosen, use the following method:

onDisplayCategory() {
    console.log("The change is successful");
    console.log(this.catSelection.value.transactionControl);
  }

Answer №3

If you want to pass the selected value from a dropdown in the child component transactions-edit.component.ts to the parent component transactions.component.ts, you can utilize @Input and @Output.

To achieve this, you may need to make some adjustments to your existing code.

Here are the modifications needed in transactions.component.html:

<app-transactions-edit (createPostEvent)="onPostCreated($event)"></app-transactions-edit>
<hr>
<div class="row">
  <div class="col-xs-12">
    <form [formGroup]="catSelection">
      <select 
        formControlName="transactionControl" 
        (change)="onDisplayCategory()">
    <option [ngValue]="transactionCategory" *ngFor="let transactionCategory of transactionCategories">{{transactionCategory}}</option>
    </select>
    </form>
  </div>
<div></div>
</div>

Add this new method in transactions.component.ts:

onPostCreated(postData: Transaction) {
    console.log("onPostCreated", postData)
    this.catSelection.controls['transactionControl'].patchValue(postData.category)
}

Changes required in transactions-edit.component.ts:

import { Component, Input, Output, OnInit, EventEmitter } from '@angular/core';
import { DataStorageService } from '../../shared/data-storage.service';
import { Transaction } from '../../shared/transaction.model';


@Component({
  selector: 'app-transactions-edit',
  templateUrl: './transactions-edit.component.html',
  styleUrls: ['./transactions-edit.component.css']
})
export class TransactionsEditComponent implements OnInit {

  @Output() createPostEvent = new EventEmitter()

  constructor(private dsService: DataStorageService) { }

  ngOnInit() {
  }

  onCreatePost(postData: Transaction) {
    this.dsService
      .createAndStorePost(postData.name, postData.amount, postData.category)
      .subscribe(responseData => {
        console.log(postData)
        this.createPostEvent.emit(postData)
      })

  }
}

You can refer to the source code on this link.

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

Oops! Only one request should be open, but it seems there is one too many

I'm encountering an issue while trying to run HTTP unit test cases. My Angular version is 5. Can someone help me with resolving this? Here is the code snippet for a basic GET request: import { TestBed } from '@angular/core/testing'; import ...

Can PassportLocalDocument and PaginateModel coexist within the same framework?

I am new to TypeScript and NestJS, looking to implement a pagination feature for all models in my application. Currently using NestJS with Mongoose for the API project. Here is an example of the user schema: export const UserSchema = new mongoose.Schema( ...

Leveraging private members in Typescript with Module Augmentation

Recently, I delved into the concept of Module Augmentation in Typescript. My goal was to create a module that could inject a method into an object prototype (specifically a class) from another module upon import. Here is the structure of my folders: . ├ ...

Display the inputs from a reactive form in a different component

I am currently facing a situation where I have multiple components, such as component A, containing a reactive form. The data from these forms is stored in a central service. My goal now is to display a preview of this form in component B. However, upon na ...

Error TS2322: This type cannot be assigned to type 'never' in Angular

Trying to incorporate the websocket (sockjs and stomp) into my Angular project for a chat messaging feature, I encountered an issue in my service.ts file. Specifically, when I defined the addMessage method like so: public messages = []; addMessage(messa ...

How to use $$[n] in Spectron/WebdriverIO to target the nth child element instead of the selector

Attempting to utilize Spectron for testing my Electron application has been challenging. According to the documentation, in order to locate the nth child element, you can either use an nth-child selector or retrieve all children that match a selector using ...

Tips for accurately defining prop types in next.js when utilizing typescript?

Here is the content of my index.tsx file: import type { NextPage } from "next"; type AppProps = { articles: { userId: number; id: number; title: string; body: string; }; }; con ...

Angular 2 Typescript: Understanding the Structure of Member Properties and Constructors

I am currently exploring a project built with Ionic 2, Angular 2, and Typescript, and I find myself puzzled by the way member properties are being set. In the code snippet below, I noticed that Angular automatically injects dependencies into the construc ...

Incorporate axios within getStaticProps while utilizing Next.js

I am working on a new project where I am utilizing axios to handle request data. However, I am facing an issue when using axios in the getStaticProps function which results in an error on my index.js page. Here is a snippet of my index.js code: import ...

Concealing a column within an Angular Material table

I'm currently faced with a challenge involving an Angular Material table containing numerous columns. My goal is to selectively hide certain columns based on specific CSS media queries. This is the code snippet I have experimented with so far: HTML: ...

How to retrieve the current route name or URL in AngularDart5

Exploring the OnActivate feature in Angular docs, I am attempting to utilize it to dynamically update the UI based on the current route. @Component( selector: "blah", template: """blah""", directives: const [routerDirectives]) class Blah ext ...

The power of Angular 18's new @let syntax for template rendering

The latest update from the Angular team introduces a new @let syntax in templates. As mentioned in this comment, this feature is now available in this commit, which has been rolled out in version 18.0.2. I have updated my NX workspace to use @angular/comp ...

Learn how to bring a component into another component within Angular

I have developed a component named CopySchedulefromSiteComponent and now I am looking to import it into another component called SiteScheduleComponent. However, I am unsure of the correct way to do this. The CopySchedulefromSiteComponent contains one fiel ...

Showing identification and name within a URL path - Angular

I am looking to update a URL path within a website from http://localhost:4200/viewbrand/1 to http://localhost:4200/viewbrand/1/soap, where "soap" is added after the ID in the path. The current code in the routing module.ts file is as follows: { path: &apo ...

The absence of a type error is not being flagged when it is expected to appear

I'm puzzled as to why this code is not throwing a type error, even though it clearly should. Instead of an error, I am seeing the output: Hello 34 Below is my code snippet: @Component({ selector: 'test', template: ` <h1 ...

Tips for composing content on a sanitized input?

In my small application, I have a feature where a question is displayed with certain words hidden and needs to be filled in by the user. The format of the question looks like this: The {0} {1} {2} his {3} off To achieve this functionality, I wrote the f ...

Tips for showcasing the information from a JSON document in React

I have a JSON file stored statically in my public directory and I'd like to show its content within a React component (specifically NextJS). The goal is to simply render the JSON as it is on the page. import data from '../../public/static/somedat ...

Unable to modify translation values in an existing ngx-translate object

I am facing an issue where I am unable to change the value of an object property within a translation JSON file using ngx translate. Despite attempting to update the value dynamically when receiving data from an API, it seems to remain unchanged. I have t ...

Guide on setting and retrieving values with a service using a map function

I have a shared HTML <inventory-products-list *ngIf="toggle" [products]="products" (qrCode)="generateQRCode($event)" (undeleted)="undelete($event)" (deleted)="deleteProduct($event)"></inventory-products-list> this I need to use in different ...

What allows us to create an instance of a generic class even without defining the generic type parameter?

It is intriguing how TypeScript allows the instantiation of a generic class without specifying the actual generic type parameter. For instance, in the code snippet below, the class Foo includes a generic type parameter T. However, when creating a new Foo i ...