The value from select2 dropdown does not get populated in my article in Angular

I am attempting to link the selected value in a dropdown menu to an article, with a property that matches the type of the dropdown's data source. However, despite logging my article object, the property intended to hold the selected dropdown value appears empty.

Below is a snippet of my code:

In typescript I have :

article: Article;
mainGroups: Group[];
subGroups: Group[];

During initialization, I fill mainGroups and subGroups with data as follows:

 ngOnInit() {
    this._groupService.getAll().subscribe(groups => this.mainGroups = groups);
    this._groupService.getAllSubGroups().subscribe(subgroups => this.subGroups = subgroups);
  }

Then, in the html file, I iterate over values from my mainGroups and subGroups arrays like so:

<div class="form-group">
  <label class="control-label dash-control-label col-xs-3">Main group:</label>
  <div class="col-xs-9">
    <select class="form-control dash-form-control select2" style="width: 100%;"
            data-minimum-results-for-search="Infinity" name="articleGroups" required [(ngModel)]="article.mainGroup">
      <option disabled [ngValue]="null">-/-</option>
      <option [ngValue]="group" *ngFor="let group of mainGroups">{{group.title}}</option>
    </select>
  </div> 
</div>

<!--Sub group-->
<div class="form-group">
  <label class="control-label dash-control-label col-xs-3">Sub group:</label>
  <div class="col-xs-9">
    <select class="form-control dash-form-control select2" style="width: 100%;" name="subGroup" required [(ngModel)]="article.subGroup">
      <option disabled [ngValue]="null">-/-</option>
      <option [ngValue]="subgroup" *ngFor="let subgroup of subGroups">{{subgroup.title}}</option>
    </select>
  </div>
</div>

In the above code, I specify [(ngModel)]="article.mainGroup" on the first dropdown along with

[ngValue]="group" *ngFor="let group of mainGroups"
.

Therefore, does the [ngValue]="group" retrieve the value from the *ngFor loop and assign it to article.mainGroup?

However, when I log article to the console, the article.mainGroup property seems to be missing entirely, even though it is defined in the article.ts model. Does this mean that the article.mainGroup property is empty (as it is not visible in console.log(article))?

Answer №1

If you're looking for a solution, consider implementing this:

<select class="form-control" [(ngModel)]="size" name="sizeValue" #sizeValue="ngModel">
  <option *ngFor="let size of sizes" [value]="size">{{size}}</option>
</select>

Make sure to include #sizeValue="ngModel" as shown above.

You can refer back to my initial response by visiting:

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

Is it possible to define a shared function for enums in TypeScript?

I have created an enumeration called VideoCategoryEnum: enum VideoCategoryEnum { knowledge = 0, condition = 1, interview = 2, speech = 3, entertainment = 4, news = 5, advertisement = 6, others = 7, } I am looking to implement a shared met ...

Access data from JSON array in Angular 2

I'm facing a basic issue here. I have a JSON file named pageDefinition.json that is being loaded into my component. Here's how the JSON data looks: ... "testArray": [ {"id": 0, "name": "row1"}, {"id": 1, "name": "row2"}, {"id": 2, "n ...

Issue encountered in cdk-virtual-scroll-viewport upon modifying the item array

Encountering an issue with a list of products displayed in a virtual scroll. The problem arises when the array of items is altered. For instance: Initially, there are 100 items in the scroll. Upon running the "reloadItems()" function to change the 100 i ...

Different color for background of division

I am working with a structure that looks like this: <div class="wrapper"...> <a href="#"...>blah</a> <div class="post"...>stuff</div> </div> This structure repeats multiple times on a dynamic page. I am looking f ...

Tips for accessing properties in JSON objects using AngularJS

In my Angular project, I have a TypeScript class called CheckoutInfo. export class CheckoutInfo { lines: CheckoutInfoLine[]; taxRate: number; get subTotal(): number { return this.lines.reduce((acc: number, cur: CheckoutInfoLine) => ...

Inheritance-based type inference

I have created a class hierarchy to manage inheritance in my code. Here is an example of how it looks: class A { clone(): A { return new A() } methodA() { return this.clone() } } class B extends A { clone(): B{ return new B() } ...

Ajax external variable

I successfully uploaded a json file via Ajax using vanilla JS. { "list": [ {"name": "Executor", "date": "19.04.2017, 12:32:57"}, ... ] } Although I am able to change the "date" value for the current one using addEventListener, my challenge no ...

Tips for filtering only alpha versions, such as those labeled 1.0.0-alpha.*

Is it possible to specifically target -alpha versions of a package using semver and NPM? The common approaches like using 1.0.0-alpha.x or * do not seem to work as expected due to how the version elements are interpreted. The usage of ~1.0.0-alpha also do ...

Extracting values from an *ngFor loop in Angular 8 - Here's how to do

Currently, I am utilizing *ngFor to display some data. I have a requirement to extract a specific value from *ngFor and display it in, for instance, my heading. However, when I attempted to use {{ project }}, it consistently returned undefined. Despite hav ...

Cordova - Fixed elements flicker/blink when scrolling

I have exhausted all possible solutions, ranging from -webkit-transform: translate3d(0,0,0); to -webkit-backface-visibility:hidden but none of them seem to resolve the issue of an element flickering/blinking/disappearing when scrolling on iOS with - ...

What could be causing my JSON product list to not load properly?

My list is not loading and I can't figure out why. I've included my json, jquery, and HTML below. The console isn't showing any errors, but the list is still blank. Any help would be greatly appreciated as I am new to working with json. Than ...

Using template strings in one-way binding: a beginner's guide

Are you familiar with combining template strings with interpolation? This particular line is not functioning correctly. <a [href]='`#/emailing/scenario/${marketing._id}`'>{{marketing.name}}</a> Thank you! PS: I understand that the a ...

Ensure that the promise is fulfilled only if a specific condition is met

I have a complex if-else condition in my code that includes different promises. Once the logic determines which condition to enter and executes the corresponding promise, I need to ensure that a final promise is always executed. if (a < 5) { vm.pr ...

What is the best approach for implementing line coverage for object literal in Typescript Mocha unit-tests?

Lead: I am a newcomer to using typescript and writing unit tests with Mocha and Chai. Question: Can anyone provide tips on achieving 100% line coverage in unit tests for an object literal that isn't within a class? I want to avoid going static if pos ...

Automating testing with JavaScript and Selenium WebDriver

Can testing be automated using the combination of JavaScript and Selenium? I am not familiar with Java, Python, or C#, but I do have expertise in Front-End development. Has anyone attempted this before? Is it challenging to implement? Are there any recom ...

Promise Pending awaiting response from function

Could someone please explain why the code I have written below is returning a Promise pending value for the 'out' variable? var out = dbConn.connect().then(function (){ var request = new sql.Request(dbConn); request.input("termin ...

Leveraging external data for testing in Protractor script

I am encountering an issue while attempting to access test data using JSON, as it keeps showing up as undefined. I am implementing a Page Object Model and trying to reference external test data. However, when passing the values from my test data into a fun ...

Managing and enumerating array elements in an angular.js controller

In my Angular application, I am working with an array of objects that each contain a "ready" field storing a timestamp. My goal is to determine the count of objects where the "ready" timestamp is earlier than the current time. How can I achieve this? This ...

What is the best way to output a received HTML page from the server?

I'm currently working on printing an HTML page that was generated using Node.js on my server. After sending the page to the client side as a response to an AJAX request, I have stored it in a JavaScript variable. var resp_json = printRequest.getRespo ...

Exploring the wonders of Node.js, Redis, and Express.js while navigating through the enchanting world of Asynchronous

Hello there, I must confess that this is a whole new realm for me... Here is what we've got: app.get('/user/:user_id/followings', function(req, res) { var response = {} , userId = req.params.user_id , ids = req.param(' ...