如何在 selecting angular 中的另一个 ng-select 下拉菜单时重置 ng-select?

How to reset ng-select upon selecting another ng-select dropdown in angular?

我在代码中有 3 个 ng-selects,如下所示,如何在 selecting 任何一个时重置其他 selections。就像如果我 select selectOne,那么 selectTwo 和 selectThree 应该被重置。我正在使用 ng-select 库。

<ng-select id="selectOne" formControlName="name1" (change)="someFun()">
   <ng-option *ngFor = "let x of y" [value]="somevalue">{{somevalue}}</ng-option>
</ng-select>

<ng-select id="selectTwo" formControlName="name2" (change)="someFun()">
   <ng-option *ngFor = "let x of y" [value]="somevalue">{{somevalue}}</ng-option>
</ng-select>

<ng-select id="selectThree" formControlName="name3" (change)="someFun()">
    <ng-option *ngFor = "let x of y" [value]="somevalue">{{somevalue}}</ng-option>
</ng-select>

您可以编写一个方法来重置其他变量,将更改后的 select 作为参数传递,然后遍历所有其他变量名称并重置它们的值。

resetOther(changedVariable) {
    ['variable1', 'variable2', 'variable3'].filter(k => k != changedVariable).forEach(k => {
        this[k] = undefined;
    });
}

您的模板

<ng-select id="selectOne" formControlName="name1" [(ngModel)]="variable1" (ngModelChange)="resetOther('variable1')">
   <ng-option *ngFor = "let x of y" [value]="x">{{x}}</ng-option>
</ng-select>

为了您更好地理解,我以州及其城市列表为例。

Html代码:

<label>Country</label>
<div  title="Please select the country that the customer will primarily be served from">
    <select placeholder="Phantasyland" (change)="changeCountry($event.target.value)">
        <option *ngFor ="let count of countryList">{{count.name}} </option>
    </select>
</div>


<label>City</label>
<div title="Please select the city that the customer is primarily to be served from.">
    <select placeholder="Anycity">
        <option *ngFor ="let city of cities">{{city}} </option>
  </select>
</div>

TS代码:

countryList: Array<any> = [
    { name: 'Germany', cities: ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn'] },
    { name: 'Spain', cities: ['Barcelona'] },
    { name: 'USA', cities: ['Downers Grove'] },
    { name: 'Mexico', cities: ['Puebla'] },
    { name: 'China', cities: ['Beijing'] },
  ];
  cities: Array<any>;
  changeCountry(count) {
    this.cities = this.countryList.find(con => con.name == count).cities;
  }

注意 * 请对您的第三个下拉菜单执行相同的操作。