kan*_*dan 3 custom-component typescript angular
我已经按照http://almerosteyn.com/2016/04/linkup-custom-control-to-ngcontrol-ngmodel上的教程来创建自定义元素.
有一个包含两个字段的表单:一个自定义组件和另一个通过ngmodel链接到同一字段的组件(输入字段).
当我编辑自定义组件中的值时,它会抛出异常"ORIGINAL EXCEPTION:表达式在检查后已更改.".但是,正常字段中的更改会触发正确更改自定义元素.
这是代码:
<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" />
Run Code Online (Sandbox Code Playgroud)
和自定义元素:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
它在使用enableProdMode()时解决; 但不能在开发中使用它
****错误(Chrome输出):
core.umd.js:5995 EXCEPTION:./MFormComponent类中的错误MFormComponent - 内联模板:55:117引起:表达式在检查后发生了变化.以前的价值:'surtest'.当前价值:'surtes'.
core.umd.js:5997原始异常:表达式在检查后发生了变化.以前的价值:'surtest'.当前价值:'surtes'
在ExpressionChangedAfterItHasBeenCheckedError.Error(native)的ExpressionChangedAfterItHasBeenCheckedError.BaseError [作为构造函数](http:// localhost:8085/templatetest/js/@ angular/core/bundles/core.umd.js:1456:38)处于新的ExpressionChangedAfterItHasBeenCheckedError(http) :// localhost:8085 /templatetest/js/@angular/core/bundles/core.umd.js:8078:20)
我想这是因为你使用相同formControlName="surename1"的<custom-component>和<input>.
如果要将它们绑定到同一模型,则只指向ngModel它,但为每个模型创建一个控件.
| 归档时间: |
|
| 查看次数: |
4233 次 |
| 最近记录: |