首页 > 解决方案 > 基于 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

标签: angulartypescript

解决方案


你可以得到你选择的下拉值,如下所示。

onDisplayCategory() { console.log("change works"); console.log(this.catSelection.value.transactionControl); }


推荐阅读