Angular 2 无法为 ControlValueAccessor 组件设置默认值

Angular 2 can't set default value for ControlValueAccessor component

按比例缩小 plunkr:https://plnkr.co/edit/gGCiYjcq70xaewn3n22F?p=preview

@Input() model: any;

propagateChange = (_: any) => {};

registerOnChange(fn) {
  this.propagateChange = fn;
}

registerOnTouched() {}

writeValue(value: any) {

  if (value !== undefined) {
    this.model = value;
  }
}

ngOnInit() {

  // Sets the model properly, but it doesn't show up in the view or outside of the component
  if (!this.model && this.isRequired) {
    this.model = options[0];
  }

  this.propagateChange(this.model);
}

用法:

<form #myForm="ngForm">
  <custom-select #fuel="ngModel" [(ngModel)]="model.fuel" [options]="fuels" [isRequired]="true" name="fuel"></custom-select>
</form>

我已经为自定义 select 实现了 ControlValueAccessor,但是在 ngOnInit 方法中首次初始化组件时,我无法让它设置默认值。 model 已在组件内部正确设置,但未反映在视图中或组件外部。但是,如果我然后通过 selecting 一些其他选项来更改值,它会起作用。有人知道这是为什么吗?

您可以使用以下方法使其正常工作

@Output() ngModelChange = new EventEmitter();

ngOnInit() {
 ...
 this.ngModelChange.emit(this.model);
}

https://plnkr.co/edit/VQJSDLU9TP2rVBmNeTNr?p=preview

我认为这是最干净的方式:

registerOnChange(fn: any): void {
  this.propagateChange = fn;
  if (this.value == null) {
   this.propagateChange('defautlValue');
  }
}