user8334943
user8334943

Reputation: 1557

proper way to implement dropdowns in ng2?

What is the proper way to implement dropdowns in ng2? I did some googling but I wasn't finding a lot of consistency.

My search.component.ts has a searchMetadata property which gets set via ngOnInit().

searchMetadata.Authors looks like [{Id=1, Value="Bob Smith"},{Id=2, Value="Mary Jones"}]

The final ng2 dropdown should be something like this:

<select #ddlAuthor (change)="updateSearchResults()">
    <option value="1">John Smith</option>
    <option value="2">Jane Doe</option>
    <option value="3">John Denver</option>
</select>

What is the proper way to implement ng2 for this in the component.html?

Upvotes: 0

Views: 47

Answers (2)

Alexander Staroselsky
Alexander Staroselsky

Reputation: 38827

You can use *ngFor to iterate over an array/collection populate the value and text accordingly. I've updated the answer to simulate a delay of 3000ms before setting the values to mimic an HTTP API call.

HTML:

<select #ddlAuthor (change)="updateSearchResults($event)">
    <option *ngFor="let option of options" [value]="option.Id">{{option.Value}}</option>
</select>

TS:

export class App {
  options: any[];

  constructor() {}

  ngOnInit() {
    // simulated delay for API call
    Observable
      .of([
        {Id:1, Value:"Bob Smith"},
        {Id:2, Value:"Mary Jones"}
      ]).delay(3000).subscribe(values => {
        this.options = values;
      });
  }

  updateSearchResults($event) {
    console.log($event);
  }
}

Here is a plunker demonstrating the functionality.

Note: The array you referenced in your question [{Id=1, Value="Bob Smith"},{Id=2, Value="Mary Jones"}] is not valid JavaScript syntax. Objects are structured as { key: value }, it would need be a colon ":" character between the key and value rather than a equal sign "=" like in C# Object Initialization. Having the "=" will cause errors in your Angular application.

Hopefully that helps!

Upvotes: 2

user8334943
user8334943

Reputation: 1557

This works:

<select (change)="updateSearchResults()" #ddlAuthor>
    <option *ngFor="let author of blogSearchMetadata.Authors">{{author.Value}}</option>
</select>

Upvotes: 1

Related Questions