I am facing an issue with a dynamic select element in Angular. I am struggling to display the selected values on the view because I cannot seem to create a click event on the dropdown options or access the selected option via a click event on the <select>
tag.
Below is the HTML code snippet:
<router-outlet></router-outlet>
<hr>
<div class="row">
<div class="col-xs-12">
<form [formGroup]="catSelection">
<select
formControlName="transactionControl"
(change)="onDisplayCategory()">
<option [ngValue]="transactionCategory" *ngFor="let transactionCategory of transactionCategories">{{transactionCategory}}</option>
</select>
</form>
</div>
<div></div>
</div>
And here is the TypeScript code:
import { Component, OnInit } from '@angular/core';
import { DataFetchingService } from '../shared/data-fetching.service';
import { Transaction } from '../shared/transaction.model';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-transactions',
templateUrl: './transactions.component.html',
styleUrls: ['./transactions.component.css']
})
export class TransactionsComponent implements OnInit {
result: Transaction[]
transactions: Transaction[]
transactionCategories: Set<string>
catSelection: FormGroup;
constructor(private dfService: DataFetchingService) { }
ngOnInit() {
this.catSelection = new FormGroup({
'transactionControl': new FormControl(null)})
this.loadPosts()
}
loadPosts() {
this.dfService.fetchData().subscribe(
posts=>{
this.transactions=posts;
this.transactionCategories = new Set<string>(posts.map(p => p.category))
console.log(this.transactionCategories)
console.log(this.transactions)
}
)
}
onDisplayCategory() {
console.log("change works")
}
}
You can view the implementation on Stackblitz: https://stackblitz.com/edit/angular-6ni1pg