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;