背景
我从包含HTML的服务器接收客户端生成的数据,然后我用它来创建一个动态组件,该组件将被注入并显示在我们的客户端中 . The HTML I receive can contain one or many inputs that I need to bind to via Angular Reactive Forms .
尝试1:
我试图通过简单地使用 [innerHTML]
属性并创建动态Reactive Forms来绑定到输入来解决此要求 . 但是,由于使用innerHTML属性的技术限制,该方法失败 . Once the HTML is rendered in the browser all properties are forced to lowercase text so any Angular directives or properties then fail . 比如 *ngIf, *ngFor, [formGroup], formControlName
等...... Angular使用camelCase几乎所有东西,因此一旦它被强制为小写文本,它就会被忽略,这种方法不再是一个可行的解决方案 .
尝试2:
这次我试图利用Angulars NgTemplateOutlet动态地将HTML添加到组件,然后创建并绑定到Reactive Form . This at first seemed like a great solution, but ultimately in order to get the html to render it requires the use of the [innerHTML] property, once again rendering this method useless (as described in my first attempt) .
尝试3:
At last I discovered Dynamic Components ,此解决方案正在部分工作 . 我现在可以成功地创建一个格式良好的Angular HTML模板,该模板在浏览器中正确呈现 . 然而,这只解决了我的一半要求 . At this point the HTML displays as expected, but I have been unable to create a Reactive Form and bind to the inputs .
问题
我现在有一个动态组件生成HTML,其中包含我需要通过创建一个Reactive Form来绑定的输入 .
尝试4:
我尝试将所有逻辑用于在创建的动态组件中创建Reactive Form .
By using this method the dynamic components HTML is displayed, but I get a new error: "ERROR Error: formGroup expects a FormGroup instance. Please pass one in."
2 回答
解决方案
Working StackBlitz with solution
The solution is to create the Reactive Form in the parent component. Then use Angulars dependency injection and inject the parent component into the Dynamic Component.
By injecting the parent component into the dynamic component you will have access to all of the parents components public properties including the reactive form. 此解决方案演示了如何创建和使用Reactive Form绑定到动态生成的组件中的输入 .
Full code below
如果我正确读取此内容,您的模板(HTML)将超出组件初始化,特别是在
FormGroup
上 . 防止这种情况发生的最好方法是将*ngIf
语句附加到您绑定FormGroup
的表单上 . 这样,在定义FormGroup
之前,它不会呈现 .