angular ng-select 如何使用模板表达式设置 selected 值

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

angular ng-select 如何使用模板设置 selected 值。例如这样的东西,

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

我正在使用 angular2-select npm 包。我想让 Input 属性代替 ngModel 执行任务。

我通过用自定义组件包装 ng-select 组件来解决这个问题。

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

并在组件中为 'ControlValueAccessor' 实现了接口方法。

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 模板,

<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>

我认为您应该将 bindValue 输入添加为 bindValue="value"