I'm having trouble populating a select menu

I am currently working on populating a select element in Angular with data. I found an example online that I'm using, but I am unable to see anything rendered on the HTML page. The plan is for the data to eventually come from a service, but for now, I am testing it with hardcoded data. Initially, the example used ngModel, which was causing errors. I attempted to switch it to formGroup, but I'm unsure what should be included inside.

     areas: Area = {
        id: 1,
        nombre: "Contabilidad"
      };
    
     onSelect(id: any): void{
        console.log('id ', id);
      }
    
<form class="theForm" (ngSubmit)="onSubmit()" [formGroup]="myForm">

    <br><br>
    <label >Area </label><br>
          <select [formGroup]="myForm." (change)="onSelect($event.target.value)">
              <option *ngFor="let area of areas" value={{areas.id}}>
                 {{areas.nombre}}
              </option>
    </select>
    <br><br>

errors:

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

this.form._updateTreeValidity is not a function

The data fetched from the service will consist of collections of IDs and names

Answer №1

  1. According to @Arcteezy, areas is not considered an Array. It should be updated to:
     areas: Area[] = [
      {
        id: 1,
        nombre: "Contabilidad"
      }
     ];

  1. When using the ng-if, make sure to reference the item (area) instead of the entire Array (areas): Use value={{area.id}} and {{area.nombre}}.

Answer №2

Let's address your TypeScript concerns first. The issue lies in the incorrect definition of your array. Instead of creating an array, you are creating an object. Therefore, your areas array should be structured like this:

areas: Area[] = [
    { id: 1, nombre: 'Contabilidad' },
    { id: 2, nombre: 'RRHH' },
    { id: 3, nombre: 'Finanzas' }
]

Now moving on to the Angular aspect. You seem to be utilizing Angular Reactive Forms, which is great. However, there seems to be a mistake in your markup. Start by creating a myForm object using the provided FormGroup/FormBuilder API and create a nombreArea FormControl:

...

import { FormBuilder, Validators } from "@angular/forms";

...

export class AreaComponent {

  constructor(public fb: FormBuilder) { }

  ...

  myForm = this.fb.group({
    nombreArea: [null]
  });

  onSelect(event) {
    console.log(event);
  }

}

In addition, ensure that your select is a FormControl, not a FormGroup. Here is the corrected structure:

<select class="area-select" (change)="onSelect($event)" formControlName="nombreArea">
   <option value="" disabled>Seleccionar Area</option>
   <option *ngFor="let area of areas" [ngValue]="area.id">{{area.nombre}}</option>
</select>

With these adjustments, the select element will display a default option ("Seleccionar Area"), show the area.name, and use the area.id as the selected value.

While Reactive Forms may require more effort initially, they prove to be highly beneficial once mastered.

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

Access granted to endpoint

I decided to implement a custom decorator for authentication across all controllers in my nest application. Here's the code snippet: export function AuthRequired(exposeOptions?: ExposeOptions): (arg0: Controller, arg1: string, arg3: TypedPropertyDescr ...

Unable to modify the text in the input field as the input element cannot be located, despite its presence

Currently, I am running some tests on a web service using Selenium. An issue I encountered is that certain elements get altered by Angular, making it difficult to interact with them as expected. One specific problem I faced was trying to modify text in wha ...

Angular 5: Implementing Form Validation in a Modal Component Using ng-template

Within the HTML file of the parent component, specifically in 'workorders.component.html', there is a modal defined as an 'ng-template' which contains a child component called 'app-generic-form'. The 'app-generic-form&ap ...

How to Retrieve Grandparent Component Attributes in Angular Using Grandchild Components

I am constructing an Angular application and facing the challenge of accessing a property of Component 1 within Component 3. In this scenario, the relationship is described as grandparent-grandchild. Successfully establishing communication between parent/ ...

Extract particular "set" from JSON retrieval

For instance, here is a sample output, but the JSON response will be much longer. I am only interested in filtering out NFTs with a specific contract address (collection) from this response. Currently utilizing axios and typescript in React. { "own ...

Issues with loading Angular 4 Bootstrap JS post compiling

Utilizing normal bootstrap 3 within an Angular 4 application has been working well when compiling for development using ng serve. However, upon building the application with ng build, I encounter an issue where my bootstrap.js fails to load. Below are th ...

The Angular 2 routerLink doesn't update the component after the initial click, even though the URL changes in the browser

When using Angular 2, I encountered an issue where clicking a routerLink in the App module successfully navigates to a parameterised route (e.g. /events/2) and loads the correct component (event-details) on the initial click. However, subsequent clicks on ...

Error: Component fails to compile when imported via a module in TestBed

Struggling to write unit tests for a component that includes another component tag in its HTML. <bm-panel [title]="title" [panelType]="panelType" [icon]="icon" class="bm-assignment-form-panel"> <div *ngIf="isLoading" class="bm-loader"> ...

What causes the failure of `click()` on a WebElement?

I am currently utilizing protractor within an angular application. The page model I have is structured as follows: export interface TileElement { idx: number; icon: string; title: string; element: WebElementPromise; } getModels() { //used as wfc. ...

Make sure to include a warning in the renderItem prop of your Flashlist component

I have encountered a type warning in my React Native application. The warning is related to the renderItem prop of FlashList. How can I resolve this issue? Warning: Type 'import("/Users/mac/Desktop/project/pokeApp/node_modules/@react-native/vi ...

Error: The package [email protected] requires @angular/core@^6.0.3 as a peer dependency, but it is nowhere to be found. This error message is being misleading

Excuse my vague and whimsical question... but could someone please check this for me and confirm if I've lost my mind? Everything appears fine to me. groot@DESKTOP-F9TMEHC MINGW64 /c/mobileDev/Ionic5-go npm ls --depth="0" Ionic5-go C:&b ...

New versions of Angular (2.0.0-beta.17) are experiencing issues with module

Have you encountered any issues with importing modules in the latest version of Angular2? I've noticed that the module names have been updated, for example angular2/core has been changed to @angular/core. Despite this change, I keep getting an error f ...

How to compare and filter items from two arrays using TypeScript

I am looking to filter out certain elements from an array in TypeScript Original Array: [ {"Id":"3","DisplayName":"Fax"}, {"Id":"1","DisplayName":"Home"}, {"Id":&quo ...

What is the best way to sift through slug data?

Struggling to display related posts from the same category in my project using Sanity for slug data. Attempted fetching all data and storing it in the state but unsure how to filter based on the current post's category. I'm thinking about leverag ...

Is there a way to temporarily pause HTTP calls?

Looking for a solution to this problem I'm facing with the code below: while (this.fastaSample.length > 0) { this.datainputService .saveToMongoDB(this.fastaSample.slice(0, batch)) .subscribe(); } The issue is that I can't send all ...

Having difficulty generating the appropriate output for ng-new app

I am facing difficulty in generating the Angular app after running the 'ng new my-app' command. Here are the outputs I receive upon running the command - 1 Executing 'ng new-mean' app https://i.sstatic.net/UaTQe.png 2 After choosing ...

The function 'ShouldWorkController' was expected but is not defined, receiving undefined instead

Whenever I attempt to connect a controller to a template using the angular-ui-router $stateProvider, I encounter this error message: 'ShouldWorkController' is not a function. Got undefined. Surprisingly, when I define the controller within the ...

Error message in Typescript: The argument type '() => () => Socket<DefaultEventsMap, DefaultEventsMap>' cannot be assigned to a parameter of type 'EffectCallback'

I am struggling to comprehend how I should specifically type constrain in order to prevent the error within my useEffect. One approach is to either cast my newSocket or specify the return value of my useEffect as any, but I am hesitant about that solution. ...

Assign a dynamic class to an element within an ngFor iteration

I am working with a template that includes an app-subscriber component being iterated over using *ngFor: <app-subscriber *ngFor="let stream of streams" [stream]="stream" [session]="session" (speakEvents)='onSpeakEvent($event)'> ...

having issues establishing a connection between Django and Angular 2

I'm facing an issue with connecting my Angular 2 app to Django because they are running on different servers. I tried using cors but it didn't work. Any suggestions for a simple way to make the connection between them? views.py # Home Page d ...