I have been working on a project using Angular 2, where I created a dropdown component with the following code:
@Component({
selector: 'dropdown',
template: ` <div class="row" >
<div class="col-sm-3">
<select class="form-control" placeholder="--select--" >
<option
*ngFor="let value of values" (click)="selectItem(value.value)">{{value.text}}</option>
</select>
</div>
</div>`
})
export class DropdownComponent {
@Input()
values: Array<DropdownValue>;
@Output()
select: EventEmitter<any>;
constructor() {
this.select = new EventEmitter();
this.values = new Array<DropdownValue>();
}
selectItem(value) {
this.select.emit(value);
}
}
This dropdown component was then used in another component as shown below:
<dropdown [values]="categories" (select)="onselect($event)"></dropdown>
I encountered an issue while trying to access the selected value from my dropdown list within the component class.
Although using <u><li>
for dropdown creation triggers the method onselect()
, I preferred creating the dropdown list using <select><option>...
. Is there a way to access the selected value through this approach?
export class AssetComponent
{
public categories: DropdownValue[] = [
{ "value": 1, "text": "Table" },
{ "value": 2, "text": "Chair" },
{ "value": 3, "text": "Light" }
];
public isCollapsedContent: boolean = false;
searchfilter(): void {
this.isCollapsedContent = !this.isCollapsedContent;
console.log("collapsed happen");
}
onselect(value:any): void
{
console.log(value)
}
}
I aim to retrieve the selected dropdown value upon button click:
<button type="button" class="btn btn-primary" (click)="searchfilter()">
Search here
</button>