2

angular ng-select 如何使用模板设置选定值。例如这样的事情,

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

我正在使用 angular2-select npm 包。我想让 Input 属性而不是 ngModel 来完成任务。

4

2 回答 2

2

我通过用自定义组件包装 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>
于 2017-04-14T23:36:57.387 回答
0

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

于 2020-05-16T22:39:29.453 回答