Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 can't set default value for ControlValueAccessor component

Scaled down 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);
}

Usage:

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

I've implemented ControlValueAccessor for a custom select, but I can't get it to set a default value when the component is first initialised in the ngOnInit method. The model is set inside of the component correctly, but it's not reflected in the view or outside of the component. But if I then change the value by selecting some other option it works.. Does anyone know why this is?

like image 876
Chrillewoodz Avatar asked Nov 14 '16 09:11

Chrillewoodz


2 Answers

You can use the following to do it working

@Output() ngModelChange = new EventEmitter();

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

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

like image 118
yurzui Avatar answered Nov 07 '22 05:11

yurzui


I think this is the cleanest way:

registerOnChange(fn: any): void {
  this.propagateChange = fn;
  if (this.value == null) {
   this.propagateChange('defautlValue');
  }
}
like image 29
Tolga Yiğit Avatar answered Nov 07 '22 04:11

Tolga Yiğit