Chrillewoodz
Chrillewoodz

Reputation: 28368

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?

Upvotes: 9

Views: 6189

Answers (2)

Tolga Yiğit
Tolga Yiğit

Reputation: 434

I think this is the cleanest way:

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

Upvotes: 4

yurzui
yurzui

Reputation: 214295

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

Upvotes: 3

Related Questions