javascriptangulartypescript

How to initially set a value in ng-select?


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>

Solution

  • 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 codes:

    multiple: true -> stackblitz

    multiple: false -> stackblitz