Demo: https://plnkr.co/edit/cMu3lI3PkxHRErJE3T93?p=preview
I've encountered an issue with setting default values for ngModel
or formControlName
when using ControlValueAccessor
in multiple components.
For instance, in the provided demo, there is a select element that offers better user experience and visuals. However, in the ngOnInit
lifecycle hook, setting the model to be the first option in the select's choices when the select has a required
attribute set to true
seems to be problematic.
When the select has required
set to true
, it should always have a value. Currently, the default value is only set after clicking on an option.
One workaround could be to always set the value in the parent component, but this approach would result in unnecessary code duplication, which is not desired. The ability to set a default value should not be a difficult task.
Below is a snippet of the code we are dealing with:
private _model: any;
set model(val) {
this._model = val;
}
get model() {
return this._model;
}
propagateChange = (_: any) => {};
registerOnChange(fn: () => any) {
this.propagateChange = fn;
}
registerOnTouched() {}
writeValue(value: any) {
if (value !== undefined) {
this.model = value;
this.cd.markForCheck();
}
}
ngOnInit() {
if (!this.model && this.required) {
this.model = this.options[0];
}
else if (!this.required) {
this.model = null;
}
this.propagateChange(this.model);
}
Upon reviewing the demo, it is evident that setting the model in ngOnInit
is not functioning as expected.
What could be causing this issue?