This is simple custom form control
@Component({
selector: 'app-custom-control',
template: `
{{ value }}
<input [ngModel]="value" (ngModelChange)="onChange($event)">
`,
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomControlComponent),
multi: true,
}]
})
export class CustomControlComponent implements ControlValueAccessor {
private value: any;
private onChange: (val) => void;
private onTouch: () => void;
writeValue(value: any) {
this.value = value;
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouch = fn;
}
}
Used like below:
@Component({
selector: 'my-app',
template: `
<app-custom-control
[ngModel]="model"
(ngModelChange)="onChange($event)">
</app-custom-control>
<input [ngModel]="model" (ngModelChange)="onChange($event)">
`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
model = 'hello';
onChange(value) {
this.model = value;
}
}
What I fail to understand is why ngModel of the control is only being updated from changing value of the outer input, but not in the case of using inner input? Live example here: https://stackblitz.com/edit/angular-7apjhg
Edit:
Actual problem can be seen with simpler example (without inner input):
@Component({
selector: 'app-custom-control',
template: `
{{ value }}
<button (click)="onChange('new value')">set new value</button>
`,
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomControlComponent),
multi: true,
}]
})
export class CustomControlComponent implements ControlValueAccessor {
value: any;
onChange: (val) => void;
onTouched: () => void;
writeValue(value: any) {
this.value = value;
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
}
After clicking the button inside the custom control, property value on parent is updated, but ngModel is not. Updated example: https://stackblitz.com/edit/angular-tss2f3