I am trying to intialize the default value within a nested component but the native HTML element is never updated.
Root [(ngModel)]="value"
|-> Child [(ngModel)]="value"
| -> native
I have tried already constructor and ngOnInit. AfterViewInit and AfterViewChecked throws an error, that there is a value manipulation after change detection.
root template:
<child name="child" [(ngModel)]="value"></child>
child template:
<select name="childSelect" [(ngModel)]="value">
child component:
@Component({
selector: 'child',
templateUrl: './child.component.tpl.html',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => ChildComponent),
multi: true
}
],
})
export class ChildComponent implements OnInit, ControlValueAccessor {
@Input() _value: number;
private _onTouchedCallback: () => void = null;
private _onChangeCallback: (a: any) => void = null;
ngOnInit() {
this.value = 1;
// this._value = 1; // no difference
}
get value(): number {
return this._value;
}
set value(value: number) {
this._value = value;
if (this._onChangeCallback !== null) {
this._onChangeCallback(this._value);
}
}
writeValue(value: any) {
this._value = value;
}
registerOnChange(fn: any): void {
this._onChangeCallback = fn;
}
registerOnTouched(fn: any): void {
this._onTouchedCallback = fn;
}
I think I missed a small detail.