Angular2 selecting values from objects

It's starting to really bother me! I came across an array of objects and found a solution here: How to use select/option/NgFor on an array of objects in Angular2

However, even though I followed the same steps, when I log my $event it shows up as undefined. This might be because it gets stringified and then not parsed back.

Take a look at this snippet of my code:

<div class="container">
<div class="row" *ngFor="#condition of conditions;#conditionindex = index">
    <div class="col-xs-3">
        <select class="form-control" [ngModel]="stringify(condition)" (ngModelChange)="onChange(conditionindex, $event)">
            <option *ngFor="#c of catalog;#catalogindex = index" [value]="stringify(c)">
                {{c.name}}
            </option>
        </select>
    </div>
    <condition-detail [condition]="condition"></condition-detail>
</div>

<a class="btn btn-primary" (click)="newCondition()"><i class="glyphicon glyphicon-plus"></i></a>

Here is the component code as well:

export class ConditionBuilderComponent implements OnInit {
conditions: Condition[] = [];
catalog: Condition[] = [];

constructor(public _conditionService: ConditionService) { }

getConditions() {
    this._conditionService.getConditions().then(conditions => this.catalog = conditions);
}

ngOnInit() {
    this.getConditions();
}

stringify(o:any): string {
    return JSON.stringify(o);
}

onChange(conditionsIndex, selectedCondition:string): void {
    console.log(typeof selectedCondition);
    //JSON.parse(selectedCondition);
    console.log(selectedCondition);
    //this.conditions[conditionsIndex] = this.catalog[condition];
    console.log(typeof selectedCondition);
}

I could really use some assistance with this. The console log for selectedCondition keeps showing up as undefined.

Answer №1

The most recent update in Angular2 (beta 14) introduces new functionality for selecting objects as choices.

Answer №2

Understood, thank you!

Here is the solution provided:

<select class="form-control" [ngModel]="condition.name" (ngModelChange)="onChange(conditionindex, $event)">
   <option *ngFor="#c of catalog;#catalogindex = index" [value]="c.name">
                {{c.name}}
   </option>
</select>

And here is the component file:

  onChange(conditionsIndex, selectedCondition:string): void {
    this.conditions[conditionsIndex] = this.catalog.find(condition => condition.name == selectedCondition);
}

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

How to set up npm to utilize the maven directory format and deploy war files

Embarking on my very first pure front-end project, I decided to deploy it using Java/Maven. To begin, I set up a standard WAR project: │ package.json │ pom.xml │ tsconfig.json │ typings.json │ │ ├───src │ └───main ...

In Angular, there is a situation where two input fields are both referencing the same event.target

I am facing an issue where I have two input fields that are linked to the same event.target.value object, but I want them to be separate. <form class="flex-list" [formGroup]="calculation_Input" (input)="input($eve ...

How to form an array of arrays within an object using Angular framework

I'm struggling to find the optimal solution and could use some guidance. Objective There are 4 separate multiple select drop-down menus, and users can choose any combination of values from each drop-down to create a box (limited to 7 selections) by ...

Obtain the data from a different HTML element

When a user clicks on a button, I want to send the value of an input element in Angular2. What would be the most effective approach for achieving this? <input type="text" class="form-control" placeholder="Search for images..." /> <span class="i ...

What steps are needed to integrate the Prime MessageService into the Interceptor of an Angular application that exclusively utilizes Standalone Components?

I've been struggling to implement a global error notification feature, but I can't seem to inject anything into the Interceptor. The frustrating part is that there are no error messages - it simply doesn't work. If anyone has any insights on ...

Submitting a request twice with just one click of the submit button in Angular 7

I have recently created a form. <div class="clr-row campform"> <form (ngSubmit)="onSubmit(f)" #f="ngForm"> <div class="clr-col-12 gutterpadl gutterpadr"> <h5>List Name</h5> <input type=" ...

Uploading Files with Angular 2 using AJAX and Multipart Requests

I am currently working with Angular 2 and Spring MVC. At the moment, I have an Upload component that sends an AJAX request to the Spring backend and receives a response containing parsed data from a .csv file. export class UploadComponent { uploadFile: f ...

What is the correct way to include a new property in the MUI Link component using TypeScript?

Currently, within my mui-theme.ts configuration file, I have the following setup: const theme = createTheme(globalTheme, { components: { MuiLink: { variants: [ { props: { hover: 'lightup' }, style: { ...

I need to create a login form using Angular - what steps should I follow?

I'm currently in the process of developing a login form for my website. Utilizing angular, express, and mongoDB. Below is the login function controller I have implemented: loginUser: (req, res) => { User.findOne({ username: req.bo ...

What is the process for developing a type expression that can be reutilized?

Imagine having a pair of functions like the following with identical return types: private isFormArrayOrGroup(formControl: AbstractControl): formControl is UntypedFormGroup | UntypedFormArray How can I create a type that is reusable for formControl is Unt ...

What is the process for determining a variable's type programmatically and then utilizing it as the type for a function parameter?

I have a question regarding TypeScript version 4.1.5. Let's consider the scenario where I am making a GraphQL query in a function called getItems. The result, items, inherits an unnamed generated type from this function. Now, I need to perform a map ...

Encountered a problem while executing the command (npm install -g @angular/cli) on a Mac

Encountering issues while trying to set up angular/cli on my system. When attempting to run the command npm install -g @angular/cli in the terminal, I encountered error messages. Even using sudo as a prefix did not yield positive results. npm ERR! Error ...

A guide on converting JSON to TypeScript objects while including calculated properties

I have a standard JSON service that returns data in a specific format. An example of the returned body looks like this: [{ x: 3, y: 5 }] I am looking to convert this data into instances of a customized TypeScript class called CustomClass: export class ...

Angular Mat AutoSuggest - Improving User Experience

I am encountering an issue where I can retrieve the list, but as soon as I input any of my data, I receive an error ERROR TypeError: Cannot read properties of null (reading 'valueChanges'). How can I resolve this? I have verified the name of my f ...

Unable to associate with 'href' because it is not recognized as a native attribute

As a newcomer to Angular 2, I have been following a beta course on Udemy. Now that I am looking to upgrade my project to the release candidate version, I am facing an error that seems unique and not mentioned anywhere online. In my main.ts file, the code ...

Issues with Router navigation in an Ionic-Angular application

I am currently working on a straightforward application using Angular 9 and Ionic 5. The main page consists of a list of items. Here is my HTML code: <ion-header> <ion-toolbar> <ion-title>recipes</ion-title> </ion-toolba ...

Issue with Angular authentication during login attempt

I am a beginner in Angular and I'm using this method to allow users to log into the system. loginuser(){ const user = { username: this.username, password: this.password }; this.Auth.loginUser(user).subscribe((res)=>{ ...

Strange Node.js: I always avoid utilizing `require()`, yet encountered an unexpected error

For more information on this particular issue, please refer to this link It's quite puzzling as I haven't used the require() function in my code, yet I'm receiving an error telling me not to use it. How odd! The problematic code snippet i ...

Best practices for safely handling dynamic keys in Typescript

I am searching for a secure method to create keyed objects in this manner: interface Types { RED: 'RED'; BLUE: 'BLUE'; GREEN: 'GREEN'; } type TypeKeys = keyof Types; const COLORS: Types = { RED: 'RED', B ...