1

Is there a better way to implement a drop down in Angular2

I am doing the following

In the template

<select (change)="onSelect($event.target.value)">
                      <option *ngFor="#taskstatus of dropdownValues" [value]="taskstatus.value">{{taskstatus.name}}</option>
</select>

In the component class

export class CreateTaskComponent {

    public selectedStatus: Taskstatus = this.dropdownValues[0];
    public dropdownValues: Taskstatus[] = [
         {"name":"OPEN","value":"OPEN"},
         {"name":"CLOSED","value":"CLOSED"}
    ];

    onSelect(taskevent) { 
        this.selectedStatus = null;
        for (var i = 0; i < this.dropdownValues.length; i++)
        {
          if (this.dropdownValues[i].value == taskevent) {
            this.selectedStatus = this.dropdownValues[i];
            console.log(this.selectedStatus.value);
          }
        }
    }
}

class Taskstatus{
  name: string;
  value: string;
}    

Is there a simpler approach to this ?

1 Answer 1

1

Use ngModel and ngValue like:

<select [(ngModel)]="selectedStatus">
  <option *ngFor="#taskstatus of dropdownValues" [ngValue]="taskstatus">{{taskstatus.name}}</option>
</select>
Sign up to request clarification or add additional context in comments.

3 Comments

everything else stays the same ?
You don't need the onSelect method. Otherwise all can stay the same.
Ups, forgot square brackets around ngModel - added.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.