Passing variables from a template to TypeScript using ngFor

Need help passing a variable from a template to typescript using *ngFor loop.

Currently, my code looks like this:

 <select (change)="onregionchange()" data-placeholder="Regions" class="form-control regions-select" id="regions" multiple>
    <option *ngFor="let region of all_regions" [value]="region.id">{{region.name}}</option>
</select>

I want to send countries for the selected region to the ts file and store them in region.countries within the onregionchange() function.

Any suggestions on how to achieve this in angular2?

Answer №1

Ensure that when you call the onregionchange() function, all the options are passed in like this: change($event.target.options).

In your TypeScript file, make sure to extract only the selected options as you are receiving all variables. Here is an example:

onregionchange(countries) {
    this.selectedregions = Array.apply(null,countries)
      .filter(country => country.selected)
      .map(country=> country.value)
  }

You can also refer to this example for more information.

Answer №2

If you have an onchange handler on your select element, you can utilize it like this:

<select (change)="onregionchange()" data-placeholder="Regions" class="form-control regions-select" id="regions" multiple>
    <option *ngFor="let region of all_regions" [value]="region.id">{{region.name}}</option>
</select>

function onregionchange(e){
    console.log(e.target.value)
}

By setting the value of each option to region.id, you will be able to retrieve the selected region's ID in the event listener function. From there, you should be able to access other properties such as region.country.

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

What is the best way to retrieve the index of the chosen option from a select element in Angular when

My Angular application includes a simple <select> element using Material design: <mat-form-field> <mat-label>Type</mat-label> <mat-select placeholder="Type" formControlName="type" name="type" id="name"> <mat-option ...

Is it possible to consistently show the placeholder in mat-select regardless of the item currently selected?

I am looking to keep the mat-select element displaying the placeholder at all times, even if an option has been selected. Below is my HTML code: <mat-select [formControlName]="'language'" placeholder="Language"> <mat-option value=" ...

Best Practices for Converting TypeScript to JavaScript

What is the recommended approach to converting this JavaScript code into TypeScript? JAVASCRIPT: function MyClass() { var self = this, var1 = "abc", var2 = "xyz"; // Public self.method1 = function () { return "somethin ...

Every time Chrome on Android returns a keyCode of 229

Here is a snippet of code that I am having trouble with: ... @HostListener('keydown', ['$event']) onKeyDown(evt: KeyboardEvent) { console.log('KeyCode : ' + evt.keyCode); console.log('Which : ' + evt.which); ...

Implementing method overrides in TypeScript class objects inherited from JavaScript function-based classes

I am facing a challenge with overriding an object method defined in a JavaScript (ES5) function-based class: var JSClass = function() { this.start = function() { console.log('JSClass.start()'); } } When I call the start() method, it pri ...

"Experiencing sluggish performance with VSCode while using TypeScript and Styled Components

My experience with vscode's type-checking is frustratingly slow, especially when I am using styled components. I have tried searching for a solution multiple times, but have only come across similar issues on GitHub. I attempted to read and understa ...

Utilizing Angular 2 and appengine with Python to successfully pass a basic GET request

I am currently attempting to run Angular 2 on the front end and App Engine Python on the back end. To achieve this, I have launched the App Engine Python backend server using dev_appserver.py --port 3030 app.yaml, and the Angular 2 frontend server using "n ...

Bringing a JavaScript file into an Ionic/Angular 2 project

I have been attempting to integrate a simple JS library into Angular 2. The library in question is JIC.js. var jic = { /** * This function takes an Image Object (JPG or PNG) and returns a compressed new Image Object * @param {Ima ...

Tips for retrieving data from Angular Material Table source

It's great to see everyone doing well! I'm facing an issue with rendering data to a material table, and I can't figure out why it's not working. When I try to assign the data to the table's datasource for rendering, the information ...

Newly added rows do not automatically refresh in Angular's mat-table

(Angular 8) I am working with two components, addgame and home. In the home component, I am displaying all games stored in the database using a REST API. Within the home component, I am calling the game component in a dialog view using Mat-dialog. The i ...

Managing a MySQL database in NodeJS using Typescript through a DatabaseController

I'm currently working on a restAPI using nodejs, express, and mysql. My starting point is the app.js file. Within the app.js, I set up the UserController: const router: express.Router = express.Router(); new UserController(router); The UserControll ...

Personalized Validator - Inputting a Parameter

My custom validation function checks for a value in the categories field of my form. If there is a value, it then verifies if the mealTypes field is null. If it is, it marks the mealTypes as invalid. This validator function is located just outside my compo ...

Unable to create a new collection in Firebase Firestore

I encountered an issue while trying to add a collection in Firebase Firestore using the function .collection(doc).set. Despite finding the new user in authentication in Firebase, the collection was not created and the console displayed an error message. ...

Guide to retrieving Response Header in Angular 8 when making a POST request

Looking to fetch the response Header in Angular 8 after a post request and securely store the jwt token in localstorage? login(req): Observable<any> { return this.http.post(this.apiUrl + '/login', req).pipe( map(res => { if ...

Using PrimeNG checkboxes to bind objects in a datatable

PrimeFaces Checkbox In the code snippet below, my goal is to add objects to an array named selectedComponents in a model-driven form when checkboxes are checked. The object type of item1 is CampaignProductModel, which belongs to an array called selectedC ...

Navigating through React with Typescript often involves managing the process of waiting for an API call to finish

My interface structure is as follows: export interface Chapter{ id: string, code: string } Within a component, I am making an API call in the following manner: componentDidMount() { fetch("https://someapi/getchapter") .then(r ...

Error message possibly undefined when attempting to apply fill gradient to Highcharts area-spline chart

Currently working with angular 12 and utilizing highcharts. I've been attempting to fill the area spline color with a gradient, but have encountered an error in the process. Any suggestions on how to resolve this issue or what step may be causing the ...

Display a FullCalendar showcasing events for the next 30 days

I am currently working with the FullCalendar library and I have a unique request. I need to create a rolling 30-day view using the month grid style, complete with day headers. Additionally, I need the flexibility to set the starting day in the grid. For ...

Give it a little time before uploading a widget onto the page

As a newcomer to programming, I recently came across this code from an open source project. I am in the process of loading a widget onto a website. Instead of having the widget load instantly, I would like it to wait 10 seconds before displaying. Below i ...

Default interface value

I have defined an Interface as shown below: export interface IItem { name: string; isActive?: boolean; } The data structure is like this: const data: IItem[] = [ { name: 'item1', isActive: true }, { name: 'item2', ...