Chrillewoodz Chrillewoodz - 26 days ago 14
TypeScript Question

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?

Answer

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