动态插入组件时 ControlValueAccessor 不工作

ControlValueAccessor not working when component inserted dynamically

使用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 来触发 writeValue :

newComponent.instance.cd.detectChanges();

但没有运气,如何解决这个问题?我想在文本框值中看到 "Some TEXT"。

通常情况下,如果我使用此组件 html,它会正常工作。

这里是 stackblitz link 我试过的:-

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

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

我的建议是将 FormControl 输入您刚刚创建的动态 ControlValueAccessor 组件:https://stackblitz.com/edit/angular-custom-input-init-value-fuxwks

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

P.S。使用 <ng-template></ng-template> 而不是 <template></template>。这是鼓励,因为 Angular 4.