-1

动态创建基本输入组件

const compTag = 'my-input';
const template = `<${compTag}></${compTag}>`;

my-input是一个输入,它实现了ControlValueAccessor并且可以分配一个formControlName指令。

因此,将其传递给formControlName=${config.name}

const template = `<${compTag} formControlName="${config.name}"></${compTag}>`;

在我的动态组件中,传递了以下内容,以便控件找到他的父级:

viewProviders: [{
  provide: ControlContainer,
  useExisting: FormGroupDirectiv
}],

详细:

const tmpCmp = Component({
  template,
  viewProviders: [{
    provide: ControlContainer,
    useExisting: FormGroupDirective
  }],
})(class {});

后来在 DOM 中解析为:

<ng-component>
  <my-input formcontrolname="a" ng-reflect-name="a" class="ng-untouched ng-pristine ng-valid">
    <input/>
  </my-input>
</ng-component>

问题是当我尝试将任何对象配置数据传递给模板中的子组件时:

const template = `<${compTag} formControlName="${config.name}" config=${config}></${compTag}>`;

确实传递给config组件,但没有正确解析,并作为config: [Object object]

有没有人偶然发现?

4

1 回答 1

0

所以这篇文章非常有帮助。

这样,包装器组件就被免除了,并且 formControlName 直接附加到创建的组件上。

扩展答案:

formControlName上面的每个声明是什么(例如<my-input formControlName="myControl"></my-input>

下面的课程也是如此NgControl,扩展了 AbstractControlDirective课程。

它接受参数“name”,它是NameinformControlName 并且通过通过 a 扩展此类Directive,您可以从内部将组件本身分配给valueAccessor函数。

在这里建立连接(来自链接的帖子):

const component = this.resolver.resolveComponentFactory<any>(components[this.config.type]);
this.name = this.config.name; // formControlName="..."
this.component = this.container.createComponent(component);
this.component.instance.config = this.config;
this.valueAccessor = this.component.instance; // The part where NgControl is connected via ControlValueAccessor to your component.
this._control = this.formDirective.addControl(this); // The part where the control knows which is its parent in the `ReactiveForm`
于 2019-10-24T12:50:08.843 回答