【问题标题】:ControlValueAccessor not working when component inserted dynamically动态插入组件时 ControlValueAccessor 不起作用
【发布时间】:2019-04-13 13:11:46
【问题描述】:

使用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

【问题讨论】:

  • 你能创建stackblitz吗
  • 是的,我正在创建 stackblitz
  • @Chellappan - 我已经更新了 stackblitz,在此先感谢。
  • 你为什么要这样?
  • 因为我们有很多组件,不想在html中使用ngswitch,你有什么建议?

标签: angular angular6 angular-reactive-forms


【解决方案1】:

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

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

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

附:使用<ng-template></ng-template> 而不是<template></template>。从 Angular 4 开始鼓励这样做。

【讨论】:

  • 您的回答解决了问题,但我不想将 formcontrol 放到 ControlValueAccessor 组件中,正如您所建议的那样,这很 hacky :)
  • @Var 我同意,这就是为什么我建议重新考虑整个设计。
猜你喜欢
  • 1970-01-01
  • 2017-07-03
  • 1970-01-01
  • 2021-06-01
  • 1970-01-01
  • 2023-04-02
  • 2023-02-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多