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

Raj picture Raj · Mar 26, 2017 · Viewed 11.5k times · Source

angular 2 ng-select how to set selected value by using 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 Input attribute do the task instead of ngModel.

Answer

Raj picture Raj · Apr 15, 2017

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>