Search code examples
angularangular-ngselect

angular ng-select how to set selected value by using template expression


angular ng-select how to set selected value by using a template. For example something like this,

<ng-select
          [options]="[{label : "first", value : "1"}, {label : "second", value : "2"}]"
          **[value]="'1'"**
          [multiple]="false">
</ng-select>

I am using angular2-select npm package. I would like to have the Input attribute do the task instead of ngModel.


Solution

  • I got the solution to this problem by wrapping ng-select component with custom component.

      @Component({
      selector: 'ice-select',
      templateUrl: './ice-select.component.html',
      providers: [
        {
          provide: NG_VALUE_ACCESSOR,
          useExisting: forwardRef(() => IceSelectComponent),
          multi: true
        }
      ]
    })
    

    And implemented interface methods for 'ControlValueAccessor' in component.

    export class IceSelectComponent implements ControlValueAccessor, OnInit {
    
          public writeValue(value: any) {
            this.selectedValue = value;
          }
    
          public registerOnChange(fn) {
            this.propagateChange = fn;
          }
    
          public registerOnTouched(fn){
            this.propagateTouched = fn;
          }
    }
    

    HTML template,

    <ng-select
               [options]="options"
               [multiple]="false"
               [noFilter]="100"
               [allowClear]="true"
               [notFoundMsg]= "'No records found'"
               placeholder="Select"
               (selected)="onSelect($event)"
               (deselected)="onRemove($event)"
               [(ngModel)]="selectedValue"
    ></ng-select>