如何构建ng2-select级联下拉列表

时间:2017-01-20 09:42:05

标签: angular

我想使用ng2-select构建级联下拉列表。我可以让单个下拉列表工作但是当我尝试在同一视图中放置两个或更多时,只有第一个工作,第二个工作没有

import { SelectComponent } from "ng2-select/ng2-select";
import { SelectItem } from 'ng2-select/components/select/select-item';
export class AdministrativeStructureComponent implements OnInit, OnDestroy{
  @ViewChild(SelectComponent)
  private selectCountry: SelectComponent;
  private selectTier: SelectComponent;

   //Country
private countryValue: any = {};
private _countryDisabledV: string = '0';
private countryDisabled: boolean = false;
private countryItems: Array<any> = [];

constructor(
    private tierService: TierService,
    private adminStructService: AdministrativeStructureService ,
    private itemsService: ItemsService,
    private notificationService: NotificationService,
    private route: ActivatedRoute) {
    this.administrativeStructure = new AdministrativeStructure();
    this.tier = new Tier();
    this.parentTier = new Tier();
    this.GetCountries();
}
GetTiers(countryID: string) {
    this.tierService.GetTierSelect(countryID)
        .subscribe((res: TierSelectViewModel[]) => {
            this.tiers = res;
            this.tiers.forEach((tier: Tier) => {
               // console.log(tier.TierName + "====================================================================================");
                this.tierItems.push(tier.TierName);
                this.selectTier.itemObjects.push(new SelectItem({ id: tier.TierID, text: tier.TierName }));
            }, error => {
                this.notificationService.printErrorMessage("Failed to Load Tier Information " + error);
                })
        })
}
GetCountries() {
    this.adminStructService.GetCountries()
        .subscribe((res: ICountry[]) => {
            this.countries = res;
            this.countries.forEach((country: ICountry) => {
                //console.log(country.CountryName + "====================================================================================");
                this.countryItems.push(country.CountryName);
                this.selectCountry.itemObjects.push(new SelectItem({ id: country.CountryID, text: country.CountryName }));
            })
        }, error => {
            this.notificationService.printErrorMessage('Failed to load Countries. ' + error);
        });
}
//Tier
private tierValue: any = {};
private _tierDisabledV: string = '0';
private tierDisabled: boolean = false;
private tierItems: Array<any> = [];

private get countryDisabledV(): string {
    return this._countryDisabledV;
}

private set countryDisabledV(countryValue: string) {
    this._countryDisabledV = countryValue;
    this.countryDisabled = this._countryDisabledV === '1';
}

public countrySelected(countryValue: any): void {
    this.GetTiers(countryValue.id);
}

public countryRemoved(countryValue: any): void {
    //console.log('Removed value is: ', value);
}

public countryTyped(countryValue: any): void {
   // console.log('New search input: ', value);
}

public countryRefreshValue(countryValue: any): void {
    this.countryValue = countryValue;
}

//Tier
//Country Drop Down List
private get tierDisabledV(): string {
    return this._tierDisabledV;
}

private set tierDisabledV(tierValue: string) {
    this._countryDisabledV = tierValue;
    this.countryDisabled = this._countryDisabledV === '1';
}

public tierSelected(tierValue: any): void {
    //this.administrativeStructure.Parent = value.id;
    // this.router.navigate([value.id], { relativeTo: this.route });
}

public tierRemoved(tierValue: any): void {
    //console.log('Removed value is: ', value);
}

public tierTyped(tierValue: any): void {
   // console.log('New search input: ', value);
}

public tierRefreshValue(tierValue: any): void {
   // this.value = value;
}
}

我视图中的代码

<div class="row">
                     <div class="col-md-4">
                        <!--Single button with keyboard nav-->
                        <div style="width: 300px">
                            <strong>Select Country</strong>
                            <ng-select [allowClear]="true"
                                       [items]="countryItems"
                                       [disabled]="countryDisabled"
                                       (data)="countryRefreshValue($event)"
                                       (selected)="countrySelected($event)"
                                       (removed)="countryRemoved($event)"
                                       (typed)="countryTyped($event)"
                                       placeholder="No Country Selected">
                            </ng-select>

                        </div>
                    </div>
                    <div class="col-md-4">
                        <!--Single button with keyboard nav-->
                        <div style="width: 300px">
                            <strong>Select Tier</strong>
                            <ng-select [allowClear]="true"
                                       [items]="tierItems"
                                       [disabled]="tierDisabled"
                                       (data)="tierRefreshValue($event)"
                                       (selected)="tierSelected($event)"
                                       (removed)="tierRemoved($event)"
                                       (typed)="tierTyped($event)"
                                       placeholder="No Tier Selected">
                            </ng-select>

                        </div>
                    </div>

如果有人能提供一些如何做的样本,我将非常感激  感谢

2 个答案:

答案 0 :(得分:1)

在您的GetTiers方法中,您可能需要重新初始化this.tierItems数组。

您可以在subscribe方法中首先执行重新初始化。

GetTiers(countryID: string) {
    this.tierService.GetTierSelect(countryID)
        .subscribe((res: TierSelectViewModel[]) => {
            this.tierItems = [];
            this.tiers = res;
            this.tiers.forEach((tier: Tier) => {
                this.tierItems.push(tier.TierName);
            });
        });
}

如果这没有帮助,则 ng2-select 不支持此方案。您可以向第二个选择添加ngIf,并在获得数据时将其设置为true。这样,当数据已经存在时,将重新创建选择。

HTH

答案 1 :(得分:0)

以下是我为获得级联效果所做的工作

GetTiers(countryID: string) {
    this.tierService.GetTierSelect(countryID)
        .subscribe((res: TierSelectViewModel[]) => {
            this.tierItems = [];
            this.selectTier = new SelectComponent(this.element, this.sanitizer);
            this.tiers = res;
            this.tiers.forEach((tier: Tier) => {
                console.log(tier.TierID + "====================================================================================" + tier.TierName);
                this.tierItems.push(tier.TierName);
                this.selectTier.itemObjects.push(new SelectItem({ id: tier.TierID.toString(), text: tier.TierName }));
            }, error => {
                this.notificationService.printErrorMessage("Failed to Load Tier Information " + error);
                })
        })
}

我按照上一个答案的建议重新启动了items数组,但我还必须添加以下行

this.selectTier = new SelectComponent(this.element, this.sanitizer);

创建一个新的SelectComponent对象。然而,我遇到了另一个问题。

SelectItem组件的id属性的值似乎被text属性值替换。当您触发所选事件时,“value.id在这种情况下,tierValue.id”将返回“tierValue.text”的值。 登录到控制台会显示ID字段(TierID)的值

enter image description here

因此,如果ID字段对您的工作没有那么大意义,我认为这个解决方案就足以进行级联下拉