简体   繁体   中英

Set default dropdown bindLabel in @ng-select/ng-select on self change event in Angular 5/6?

I have one scenario where i want to set default value to null from self change event on ng-select . if user select dropdown first then on change event should check Amount model is not null or blank afterward if Amount model is blank then ng-select should be set to null.

The dropdown is set to null works for the first time only.

In Html component

<input type="text" [(ngModel)]="Amount"/><br/><br/>
<label>Your ng-select</label><br/>
<ng-select [items]="currencyList"
           bindLabel="name"
           bindValue="name"
           placeholder="Select Currency"
           [(ngModel)]="selectedCurrency"
           (change)="onChangeDropdown()">
</ng-select><br/>

In typescript on change event function

onChangeDropdown(){
  if(this.Amount){

  }else{
    this.selectedCurrency = null;
    alert("enter amount first");
  }
}

here i have attach link : link for dropdown example

Even i also tested in normal html select dropdown this also show me as same output above

<select [(ngModel)]="selectedCurrency" class="form-control" (change)="onChangeDropdown()">
    <option>--Select Currency--</option>
    <option *ngFor="let c of currencyList" value="{{c.id}}">{{c.name}}</option>
</select>

Why this showing still INR or other currency name on ng-select ?

I have posted same question but not find right solution here Set default dropdown bindLabel in @ng-select/ng-select on self change event in Angular? ??

You are binding ngSelect by name.

bindLabel="name"
bindValue="name"

and the selectedCurrency is the type any if you change

this.selectedCurrency = null; //to
this.selectedCurrency = {}; //it will work. just try this

Use a setTimeOut to force Angular show the null value

onChangeDropdown(){
      if(this.Amount){
      }else{
        alert("enter amount first");
        setTimeout(()=>{
          this.selectedCurrency = null;
        },0)
      }
    }

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