简体   繁体   中英

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

I have 3 ng-selects like below in code, how can I reset other selections upon selecting any one. Like if i select selectOne, then selectTwo and selectThree should be reset. I'm using ng-select library.

<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>

You could write a method to reset others where you pass the changed select as an argument and loop through all the other variable names and reset their values.

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

Your Template

<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>

For your better understanding I take a example of State and it's city list.

Html Code:

<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 Code:

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;
  }

Note * Kindly do the same for your third Dropdown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM