Angular2 - populating a list of dropdowns / dropdowns
I have a component called weekly selector. The purpose of this component is to allow the user to select the week they want to work with / view.
I am new to angular and understand the logic, however I am having problems populating this dropdown with some parameters. The following code is displayed on a page with no parameters inside the fields.
import { Component, OnInit, Input, Output } from '@angular/core';
import{EventEmitter} from '@angular/core';
export class DropdownValue {
value:string;
label:string;
constructor(value:string,label:string) {
this.value = value;
this.label = label;
}
}
@Component({
selector: 'app-week-selector',
template:
`
<form class = "ui small form segment">
<div id="WeekSubmission">
<h1> Please enter the week you are in: </h1>
<select>
<option> *ngFor="value of values" (click)="selectItem(value.value)"> {{value.label}}">
{{value}}
</option>
</select>
</div>
</form>
`
})
export class WeekSelectorComponent implements OnInit {
values:DropdownValue[];
@Output()
select:EventEmitter<string>;
constructor() {
this.values = [ new DropdownValue('Team','Liverpool')];
this.select = new EventEmitter();
}
selectItem(value){
this.select.emit(value)
}
ngOnInit() {
}
}
source to share
For one-way binding, use this since you want to track the selection changes, not just click: I assume you would like to show value.label
in the UI and write the same as the value. You can change this value according to your requirements.
<select (change)="selectItem($event.target.value)">
<option *ngFor="let value of values" value={{value.label}}>{{value.label}}</option>
</select>
// code
selectItem(value){
this.select.emit(value)
}
For two way data binding, you can use this:
<select [ngModel]="selectedValue" (ngModelChange)="selectItem($event)">
<option [value]="value.label" *ngFor="let value of values">{{value.label}}</option>
</select>
To read in detail about the types of data binding in Angular, consider reading my post on this topic .
source to share