<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" />
还有自定义元素:
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;
}
}
当使用enableProdMode();时可以解决问题,但在开发过程中无法使用
****错误(Chrome输出):
core.umd.js:5995 异常: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 原始异常:Expression has changed after it has been 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)