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

时间:2016-11-14 09:35:13

标签: angular typescript angular2-forms

缩小plunkr:https://github.com/symfony/monolog-bundle/pull/188

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

我已经为自定义选择实现了ControlValueAccessor,但是当我在ngOnInit方法中首次初始化组件时,我无法设置默认值。 model正确地设置在组件内部,但它不会反映在视图中或组件外部。但是如果我然后通过选择其他选项来改变它的作用就可以了。有人知道为什么会这样吗?

2 个答案:

答案 0 :(得分:2)

您可以使用以下方法进行操作

@Output() ngModelChange = new EventEmitter();

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

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

答案 1 :(得分:0)

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

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