Home > Net >  How to initially set a value in ng-select?
How to initially set a value in ng-select?

Time:09-26

I have ng-select with list of values. If i click on selected value and click clear , need to set first option .Please help me how to sort it out . https://stackblitz.com/edit/ng-select-wdcg5a?file=app/app.component.ts

<ng-select class="" [items]="assigneeStatus" name="status_filter_id"
           bindLabel="lookup_label" bindValue="com_lookup_id" placeholder="Assignee Status"
           [(ngModel)]="searchAssigneeObj.status_filter_id" [hideSelected]="true"
           #status_filter_id="ngModel">
    <ng-template ng-label-tmp let-item="item">
        <span>{{item.lookup_label ||  'All'}}</span>
    </ng-template>
    <ng-template ng-option-tmp let-item="item" let-search="searchTerm"
                 let-index="index">
        <span>{{item.lookup_label || ''}}</span>
    </ng-template>
</ng-select>

CodePudding user response:

You can achieve this using clear method.

in your component add below code :

public selectedCity;  

constructor() {
        this.selectedCity = [this.cities3[0]];
      }

then in the ng-select add clear event as below :

<ng-select 
     [items]="cities3"
     bindLabel="name"
     multiple = true
     placeholder="Select city"
     (clear)="resetCalculations();"
     [(ngModel)]="selectedCity">
            <ng-template ng-label-tmp let-item="item">
                <b>{{item.name}}</b> is cool
            </ng-template>
            <ng-template ng-option-tmp let-item="item" let-index="index">
                <b>{{item.name}}</b>
            </ng-template>
  </ng-select>  

and then register the handler as below :

 resetCalculations() {
    this.selectedCity = [this.cities3[0]];
  }

here is the working example : Working Demo

CodePudding user response:

There is no basic way to achieve this natively in ng-select.

You can define callback of (clear) event and add your first item in the array to achieve that goal.

HTML:

<ng-select [items]="cities3"
           bindLabel="name"
           multiple = true
           placeholder="Select at least one city"
           [(ngModel)]="selectedCities"
           (clear)="clearSelect()">
  <ng-template ng-label-tmp let-item="item">
    <b>{{item.name}}</b> is cool
  </ng-template>
  <ng-template ng-option-tmp let-item="item" let-index="index">
    <b>{{item.name}}</b>
  </ng-template>
</ng-select>    

TS:

export class AppComponent {
  selectedCities = [];
  cities3 = [
    {
      id: 0,
      name: 'Vilnius',
    },
    {
      id: 2,
      name: 'Kaunas',
    },
    {
      id: 3,
      name: 'Pavilnys',
    },
  ];

  constructor() {}

  addCustomUser = (term) => ({ id: term, name: term });

  public clearSelect() {
    this.selectedCities = [];
    this.selectedCities.push({
      id: 0,
      name: 'Vilnius',
    });
  }
}

See the code: stackblitz

  • Related