Chrillewoodz Chrillewoodz - 1 year ago 297
TypeScript Question

Angular 2 can't set default value for ControlValueAccessor component

Scaled down plunkr:

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



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

I've implemented
for a custom select, but I can't get it to set a default value when the component is first initialised in the
method. The
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 Source

You can use the following to do it working

@Output() ngModelChange = new EventEmitter();

ngOnInit() {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download