Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping over an array and displaying in dropdown - Angular

So - I have a set of data like so:

people = [
    {
      name: "Bob",
      age: "27",
      occupation: "Painter"
    },
    {
      name: "Barry",
      age: "35",
      occupation: "Shop Assistant"
    },
    {
      name: "Marvin",
      age: "42",
      occupation: "Mechanic"
    },
    {
      name: "Arthur dent",
      age: "27",
      occupation: "Human"
    },

I then also have a drop down in my html like so -

<select id='peeps' name='people'>
    <option></option>    
</select>

<div class='show-info'></div>

This is all in one component and what I am trying to do is loop over the people array, populate the options with their names and when you select that person in the drop down, their information gets displayed in the div. I have tried to start this off but I am running into a few issues.

I started doing this -

peepsSelect = document.getElementById("peeps") as HTMLElement;
populationDropdown() {
  for(var i = 0; i < this.people.length; i++) {
    var option = document.createElement("option");
    option.text = this.people[i].name;
    option.value = this.people[i].name;
    option.value = this.people[i].age;
    option.value = this.people[i].occupation;
    this.peepsSelect.add(option);
 } 
}

However I was getting error messages such as 'add does not exist on type htmlelement.


2 Answers

Try like this:

Working Demo

<select id='peeps' name='people' [(ngModel)]="peepsSelect">
    <option *ngFor="let item of data" [value]="item.name">
      {{item.name}}
    </option>    
</select>
like image 74
Adrita Sharma Avatar answered Nov 27 '25 17:11

Adrita Sharma


That is not really the Angular way of doing things. You should use two-way data binding to get this done. In addition, you can use ngValue to track the value binded to the option element. Unlike the value binding, ngValue can be used to bind to both string values and objects.

<select [(ngModel)]="selected">
  <option *ngFor="let person of people" [ngValue]="person">{{person.name}}</option>
</select>

<div class='show-info'></div>

And on your component.ts, you will need to define to above properties

export class AppComponent  {
  selected;
  people =[
    {
      name: "Bob",
      age: "27",
      occupation: "Painter"
    },
    {
      name: "Barry",
      age: "35",
      occupation: "Shop Assistant"
    },
    {
      name: "Marvin",
      age: "42",
      occupation: "Mechanic"
    },
    {
      name: "Arthur dent",
      age: "27",
      occupation: "Human"
    }
  ]
}

I have created a demo over here.

like image 38
wentjun Avatar answered Nov 27 '25 16:11

wentjun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!