动态插入组件时,ControlValueAccessor不起作用

时间:2019-04-13 13:11:46

标签: angular angular6 angular-reactive-forms

使用implements ControlValueAccessor

开发的InputFieldComponent组件
constructor(public cd: ChangeDetectorRef) {

}

onTouchedCallback = () => { };
onChangeCallback: any = () => { };

// register a handler that should be fired when something in the view has changed
registerOnChange(fn: any): void {
  this.onChangeCallback = fn;
}

// registers a handler specifically for when a control receives a touch event.
registerOnTouched(fn: any): void {
  this.onTouchedCallback = fn;
}

// writes new values from the form model into the view or any DOM property
writeValue(value: string): void {
  if (value !== this.innerValue) {
    this.innerValue = value;
  }
}

// textbox input change
onChange(event: any): void {
  this.onChangeCallback(event.target.value);
}

像这样动态添加。

const componentFactory = this.componentFactoryResolver.resolveComponentFactory(InputFieldComponent);
const newComponent = container.createComponent(componentFactory);

设置

form.addControl("firstname",
                new FormControl("Some TEXT ", Validators.required));

newComponent.instance.formControlName = "firstname"

通过在下面的行中编写来尝试触发writeValue

newComponent.instance.cd.detectChanges();

但没有运气,该如何解决?我想在文本框值中看到“某些文本”。

通常,如果我使用此组件html,则可以正常工作。

这里是我尝试过的stackblitz链接:-

https://stackblitz.com/edit/angular-custom-input-init-value-d34jls

1 个答案:

答案 0 :(得分:0)

您要混合使用模板驱动的表单(使用ngModel)和反应式表单,它们在您的Angular版本中is deprecated/possibly already removed

我建议,尽管感觉有些古怪,但还是将FormControl输入到刚创建的动态ControlValueAccessor组件中:https://stackblitz.com/edit/angular-custom-input-init-value-fuxwks

我强烈建议您重新考虑要实现的设计。

P.S。使用<ng-template></ng-template>而不是<template></template>。从Angular 4开始就鼓励这样做。

相关问题