简体   繁体   中英

How to set Dropdown value in angular4?

I have a dropdown to which i am passing some values, now i want to set the selection of the dropdown, how can i do it

here is my code

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  dataset: any[] = [
    { value: 'one', key: 1 },
    { value: 'two', key: 2 },
    { value: 'three', key: 3 },
    { value: 'four', key: 4 }
  ]

  selectionChanged(data) {
    debugger;
  }
}

html

<div>
  <select (change)="selectionChanged($event.target.value)">
      <option *ngFor="let item of dataset;let i=index " [value]="item.key" >{{item.value}}</option>
    </select>
</div>

You need to use [(ngModel)] directive.

HTML

<select [(ngModel)]="selectedItem" (change)="selectionChanged($event.target.value)">
  <option *ngFor="let item of dataset;let i=index " [value]="item.key" >{{item.value}}</option>
</select>

Typescript

this.selectedItem = dataset[0].key;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM