I have followed tutorial on http://almerosteyn.com/2016/04/linkup-custom-control-to-ngcontrol-ngmodel to create a custom element.
There is a form with two fields: one custom component and another component (input field) linked to the same field through ngmodel.
When I edit the value in the custom component, it throws the exception "ORIGINAL EXCEPTION: Expression has changed after it was checked. ". However, the change in the normal field triggers the change correctly to the custom element.
This is the code:
<custom-component [control]="surname1" [(ngModel)]="person.surname1" [name]="'surname1'" formControlName="surname1">Add surname:</custom-component>
<input type="text" name="surname2" id="surname2" formControlName="surname1" [(ngModel)]="person.surname1" />
And the custom element:
const noop = () => {};
export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MyInputComponent2),
multi: true
};
@Component({
selector: 'custom-component',
template: `<label><ng-content></ng-content></label>
<input type="text" name="{{name}}" [(ngModel)]="value"
(ngModelChange)="changed($event)"
(blur)="onBlur()"
/>
`,
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class CustomComponent implements ControlValueAccessor {
@Input() control: FormControl;
@Input() name: any;
private innerValue: any = '';
private onTouchedCallback: () => void = noop;
private onChangeCallback: (_: any) => void = noop;
//get accessor
get value(): any {
return this.innerValue;
};
//set accessor including call the onchange callback
set value(v: any) {
if (v !== this.innerValue) {
this.innerValue = v;
this.onChangeCallback(v);
}
}
//Set touched on blur
changed(event) {
this.onTouchedCallback();
}
onBlur() {
this.onTouchedCallback();
}
//From ControlValueAccessor interface
writeValue(value: any) {
if (value !== this.innerValue) {
this.innerValue = value;
}
}
//From ControlValueAccessor interface
registerOnChange(fn: any) {
this.onChangeCallback = fn;
}
//From ControlValueAccessor interface
registerOnTouched(fn: any) {
this.onTouchedCallback = fn;
}
}
it solves when using enableProdMode(); but cant use this in development
****ERROR (Chrome output) :
core.umd.js:5995 EXCEPTION: Error in ./MFormComponent class MFormComponent - inline template:55:117 caused by: Expression has changed after it was checked. Previous value: 'surtest'. Current value: 'surtes'.
core.umd.js:5997 ORIGINAL EXCEPTION: Expression has changed after it was checked. Previous value: 'surtest'. Current value: 'surtes'
at ExpressionChangedAfterItHasBeenCheckedError.Error (native) at ExpressionChangedAfterItHasBeenCheckedError.BaseError [as constructor] (http://localhost:8085/templatetest/js/@angular/core/bundles/core.umd.js:1456:38) at new ExpressionChangedAfterItHasBeenCheckedError (http://localhost:8085/templatetest/js/@angular/core/bundles/core.umd.js:8078:20)