http://almerosteyn.com/2016/04/linkup-custom-control-to-ngcontrol-ngmodelのチュートリアルに従って、カスタム要素を作成しました。
2つのフィールドを持つフォームがあります。1つはカスタムコンポーネントで、もう1つはngmodelを介して同じフィールドにリンクされたコンポーネント(入力フィールド)です。
カスタムコンポーネントの値を編集すると、「元の例外:チェック後に式が変更されました。」という例外がスローされます。ただし、通常のフィールドを変更すると、カスタム要素への変更が正しくトリガーされます。
これはコードです:
<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例外:./ MFormComponentクラスMFormComponentのエラー-インラインテンプレート:55:117原因:チェック後に式が変更されました。以前の値: 'surtest'。現在の値: 'surtes'。
core.umd.js:5997元の例外:チェック後に式が変更されました。以前の値: 'surtest'。現在の値: 'surtes'
ExpressionChangedAfterItHasBeenCheckedError.Error(ネイティブ)at ExpressionChangedAfterItHasBeenCheckedError.BaseError [コンストラクターとして](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)
私はあなたが同じを使用しているからだと推測するformControlName="surename1"
ために<custom-component>
と<input>
。
それらを同じモデルにバインドする場合は、それを指すだけでngModel
、それぞれのコントロールを作成します。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加