首页 > 解决方案 > 如何在Angular的下拉列表中显示值?

问题描述

我已经实现了 2 个下拉菜单,如下所示

在此处输入图像描述

当从第一个下拉列表中选择一个类别时,根据选择的值,它会将值分配给第二个下拉列表。

但是当应用程序第一次启动时,第一次下拉(选择类别)不会显示任何值。如果选择第二个下拉菜单(选择项目),然后当我单击第一个下拉菜单时,将分配所有值。可能是什么问题?

下面是实现

组件.html

        <div class="row ml-3 mr-3 mt-3">
            <label class="col-form-label">Select Category :</label>
            <select class="form-control" [(ngModel)]="selectedItemType" (ngModelChange)="selectItemType()">
                <option value="" [selected]="true"> Please choose one </option>
                <option *ngFor="let item of items">{{item}}</option>
            </select>
        </div>
        <div class="row ml-3 mr-3 mt-5">
            <label class="col-form-label">Select Item :</label>
            <select class="form-control" [(ngModel)]="selectedItemName" (ngModelChange)="selectItemName()">
                <option value="" [selected]="true"> Please choose one </option>
                <option *ngFor="let selectedItem of selectedItems">{{selectedItem.itemName}}</option>
            </select>
        </div>

组件.ts

import {Component, OnInit, SimpleChange} from '@angular/core';

import { DashboardService} from "@modules/dashboard/services";
import {element} from "protractor";

@Component({
  selector: 'cashier',
  templateUrl: './cashier.component.html',
  styleUrls: ['./cashier.component.scss']
})
export class DashboardItemsComponent implements OnInit {
    items : String[];
    selectedItems : {itemName : String, price : number}[] = [];
    addedItems : {itemName : String, quantity : number, price : number}[] = [];
    selectedItemType : String = ''
    selectedItemName : String = ''

  constructor(
     private dashboardService : DashboardService
  ) {
  }

  ngOnInit(): void {
        setTimeout(() => {
            this.dashboardService.getItems()
                .subscribe(response => {
                    this.items = response    //<-------- this will retrieve values for first drop down from the backend API
                })
        }, 1000)

      console.log(this.items)
  }

  selectItemType(){
     let tempSelectedItems : {itemName : String, price : number}[] = [];
        this.dashboardService.getItemsByType(this.selectedItemType)
            .subscribe( response => {
                for(let item of response){                   //<-------- this will retrieve values for second drop down from the backend API
                    tempSelectedItems.push({itemName : item.itemName, price : item.price})
                }
                this.selectedItems = tempSelectedItems;
            })
  }

  selectItemName(){
        console.log(this.selectedItemName)
  }


  add(){
        //implentation
  }
}

服务.ts

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import {map} from "rxjs/operators";
import { HttpClient } from '@angular/common/http';

@Injectable()
export class DashboardService {
    constructor(private http: HttpClient) {}

    getDashboard$(): Observable<{}> {
        return of({});
    }

    getItems(){
        return this.http.get<any>('http://localhost:8080/rest/items/types')
            .pipe(map(items => {
                if(items){
                    return items;
                }
            }))
    }

    getItemsByType(type){
        let tempSelectedItems : {itemName : String, price : number}[] = [];
        return this.http.get<any>('http://localhost:8080/rest/items/itemsByType', {params : { itemType : type}})
            .pipe(map( items => {
                if(items){
                    // return items;
                    for(let i of items){
                        tempSelectedItems.push({itemName : i.itemName, price : i.price})
                    }

                    return tempSelectedItems;
                }
            }))
    }
}

标签: angulartypescript

解决方案


代码似乎没有任何问题,如果您查看发布的 stackblitz,它们似乎可以工作。

因此,我建议您将代码精简到最低限度并从那里开始。

<div class="row ml-3 mr-3 mt-3">
    <label class="col-form-label">Select Category :</label>
    <select class="form-control">
       <option value=""> Please choose one </option>
       <option *ngFor="let item of items">{{item}}</option>
    </select>
</div>

仅从模板中的上述代码开始,看看它是否有效。我们可以从那里继续。

注意:setTimeout 不是必需的。请删除它并仅在最必要时使用它。

更新1:

constructor(
 private dashboardService : DashboardService,
 private changeDetectorRef: ChangeDetectorRef
) { }

ngOnInit(): void {
  this.dashboardService.getItems().subscribe(response => {
      this.items = response;
      this.changeDetectorRef.detectChanges(); // This should be used temporarity until the actual issue is located.
  });
}

注意 2:不要使用 String、Number、Boolean 作为类型。在它的位置,使用字符串,数字,布尔参考:https ://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html


推荐阅读