angular - 基于 Angular 中的动态选择下拉菜单显示
问题描述
我有一个动态选择,但我不知道如何在视图上显示选定的值。我很挣扎,因为显然我无法在选项上创建点击事件,而且我不知道如何通过标签上的点击事件访问该选项。
这是html:
<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>
这是ts
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")
}
}
Stackblitz:https ://stackblitz.com/edit/angular-6ni1pg
解决方案
你可以得到你选择的下拉值,如下所示。
onDisplayCategory() {
console.log("change works");
console.log(this.catSelection.value.transactionControl);
}
推荐阅读
- javascript - 有没有办法通过 onclick 函数呈现获取的数据
- gcc - 说服 cmake 在 MSYS2 中找到诅咒?
- flutter - Flutter 使用 Text 和 Icon 而不是单个 Icon 创建 PopupMenuButton
- generics - 通用结构中索引容器的向量
- c++ - 奇怪的 QPushButton 错误
- android - 具有多个实例的导航视图模型
- xcode - 如何在 RATs 软件中为 MGARCH 运行 Ljung-Box 或任何其他诊断测试?
- c++ - 是否可以从 DUMPBIN /SYMBOLS 命令派生声明的函数?
- triggers - 无法绑定到用户控件内的工具提示
- mariadb - 从 SELECT 或 UPDATE 中的不同行中查找值