Retrieve data from submit button in Angular and use it as a parameter to invoke a function

I am working on a HTML file that includes a dropdown list:

    <select>
      <option *ngFor="let t of items" value="t">
          {{ t }}
        </option>
    </select>

In addition to the dropdown list, there is also a submit button present on the same page:

<button type="button" (click)="selectedValue()" class="btn btn-info btn-sm">
  Submit
</button>

My goal is to retrieve the value that the user selects from the dropdown list. I believe this value is stored in variable "t", and I want to pass it to a function like this:

 selectedValue() {
    // calling the updateValue function with the selected value 
updateValue(t) { }
    
    
      }

This process seems a bit complex to me. I am not sure where to start - how do I transfer the selected value from the HTML to the TypeScript file and then successfully call a function to update the value and receive a successful response (status code: 200) from an HTTP request.

Answer №1

Utilize ngModel for bidirectional data binding.

To set the value for each option, you can either use the [value] directive or value="{{ t }}". Currently, every option is holding the value with the string "t," which is incorrect.

<select [(ngModel)]='selectedOption'>
  <option *ngFor="let t of items" [value]="t">
      {{ t }}
    </option>
</select>
selectedOption: string;

selectedValue() {
  this.updateValue(this.selectedOption);
}

updateValue(t) { 
  console.log(t);
}

Check out a Sample StackBlitz Demo

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

Discrepancy in Angular Material Buttons with theme design

I recently installed Angular 10 along with Angular Materials using the command ng add @angular/material I opted for the custom theme: Purple/Green The next step was to add a Toolbar by simply copying and pasting code from Google's site. However, I a ...

Tips for patiently anticipating the completed response within an interceptor

Using the interceptor, I want to display a loading spinner while waiting for subscriptions to complete. This approach works well in individual components by showing and hiding the spinner accordingly: ngOnInit() { this.spinnerService.show(); this. ...

define a variable within a v-for loop

Example of Code <div v-for="item in dataItems"> <div v-if="enableEdit"> <input type="text" v-model="name"> </div> <div v-else> {{name}} </div> <button @click="enableEdit = true">click</button> This ...

Never display mat-select panel when closed

In my current scenario, I am using the following template structure: <mat-select #select> <mat-option *ngFor="let option of optionsData"> {{ select.panelOpen ? option.viewValue : option.value }} </mat-option&g ...

Finding it challenging to adapt an AngularJs component-based modal to TypeScript

When creating an AngularJS component in JavaScript and displaying it as a modal using ui-bootstrap, you need to pass bindings that the modal instance can use for dismissing or closing itself: app.component("fringeEdit", { controller: "FringeEditCont ...

Updating the model does not reflect changes made to AGM polygons' binding

<div *ngFor="let p of polys"> <agm-polygon #cmp [paths]="$any(p.getPath()).i" [fillColor]="'blue'" [draggable]="true" [editable]="true" [polyDraggable]="true" (p ...

Tips on extracting value from a pending promise in a mongoose model when using model.findOne()

I am facing an issue: I am unable to resolve a promise when needed. The queries are executed correctly with this code snippet. I am using NestJs for this project and need it to return a user object. Here is what I have tried so far: private async findUserB ...

Having trouble accessing child directives in Angular 2 using @ContentChildren

I'm facing an issue getting nested directives from a parent directive, as @ContentChildren is not being populated. The main goal is to implement lazy-loading for images, where each image is a nested directive within the parent directive. For instan ...

One or multiple web browsers set in the Browserslist of the project

I have recently started working with the Ionic framework and encountered some warnings while setting up my application. Can anyone help me with a solution? [ng] When starting the Ionic application, I received the following warnings: [ng] One or more browse ...

Mapping JSON data from an array with multiple properties

Here is a JSON object that I have: obj = { "api": "1.0.0", "info": { "title": "Events", "version": "v1", "description": "Set of events" }, "topics": { "cust.created.v1": { "subscribe": { ...

Avoiding Maximum Call Stack Size Exceeded in Observables: Tips and Tricks

After filtering, I have a list stored in the variable filteredEvents$: public filteredEvents$ = new BehaviorSubject([]); I also have a method that toggles the checked_export property and updates the list: public checkAll(): void { this.filteredEve ...

What could be causing a blank page to appear after being redirected? (Using NextJS 13 API Route)

After struggling with this issue for 2 days, I'm throwing in the towel and reaching out to the community for assistance. I've been tasked with setting up a basic login system for a new project using NextJS v13. However, it seems like a lot has c ...

Why won't Angular 4 create the node_modules folder when using ng new to initialize a new project?

Recently reinstalled Angular and began a new project using ng new. However, I encountered issues when trying to run ng serve after creating the project and changing into its directory. On my Mac Mini, I can simply navigate to the project folder and run ng ...

A step-by-step guide for updating a minor version of Angular with Angular CLI

I've been searching online for the answer to this straightforward question, but can't seem to find it anywhere... In my angular 4 project (made with angular cli), I want to utilize the newly introduced http interceptors in version 4.3. Could so ...

Angular failing to detect Leaflet TimeDimension

Recently, I integrated leaflet-timedimension into an Angular project that utilizes ngx-leaflet. However, I encountered a hurdle when trying to utilize the geoJson time dimension feature. It appears that Angular is not recognizing the leaflet-timedimension ...

Using Tailwind classes as a prop functions correctly, however, it does not work when directly applied

Here's a component snippet I'm working on: export const TextInput = ({ label, wrapperClassName = "", inputClassName = "", labelClassName = "", placeholder = "", ...props }: InputProps & Fiel ...

Reordering items in Angular2 ngFor without having to recreate them

I am facing a unique situation where I must store state within item components (specifically, canvas elements) that are generated through an ngFor loop. Within my list component, I have an array of string ids and I must create a canvas element for each id ...

What is the best way to wrap `useFetch` in order to leverage reactivity?

When I wrap useFetch() as a composable to customize the baseURL and automatically set an authentication token, I encounter reactivity issues when calling the composable within a component without using the await keyword. Typically, I would call const { dat ...

"An issue has been noticed with Discord.js and Discordx VoiceStateUpdate where the return

Whenever I attempt to retrieve the user ID, channel, and other information, I receive a response of undefined instead of the actual data import { VoiceState } from "discord.js"; import { Discord, On } from "discordx"; @Discord() export ...

What methods can I use to make sure the right side of my React form is properly aligned for a polished appearance?

Trying to create a React component with multiple input field tables, the challenge is aligning the right side of the table correctly. The issue lies in inconsistent alignment of content within the cells leading to disruption in overall layout. Experimente ...