angular - 让子组件知道它是父组件 Angular 的 FormGroup 的一部分
问题描述
我有一个FormGroup
将它的一些字段引用到另一个使其成为子组件的组件。但是,每当我在rendering
孩子的舞台上时,我都会收到此错误
Error: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup...
当您formControlName
在FormGroup
. 我已确保父级在其子级之前首先呈现 FormGroup,并且正确地,这是默认行为。
父 HTML 是这样的。
<form [formGroup]="form.formGroup" #formDirective="ngForm" (ngSubmit)="saveForm(formDirective)">
<input matInput formControlName="form.mainInputControl" placeholder="This one doesn't have a problem" type="text">
<child-component [details]="form.detailsForChild"></child-component>
</form>
子 HTML 是这样的
<mat-checkbox formControlName="detailsForChild.checkBoxControl"></mat-checkbox>
PS:这不是真正的变量名,我只是这样做,所以它会很直观。
解决方案
显然,子组件和父组件不能像我想的那样在运行时混淆。
所以我需要将确切的信息传递FormGroup
给孩子并将其绑定到formControlName
谎言所在的更高一级的元素。
所以从例子中。
Parent
<form [formGroup]="form.formGroup" #formDirective="ngForm" (ngSubmit)="saveForm(formDirective)">
<input matInput formControlName="form.mainInputControl" placeholder="This one doesn't have a problem" type="text">
<child-component [details]="form.detailsForChild" [parentForm]="form.formGroup"></child-component>
</form>
孩子
<ng-container [formGroup]="parentForm">
<mat-checkbox formControlName="detailsForChild.checkBoxControl"></mat-checkbox>
</ng-container>
参考:这里
推荐阅读
- html - 为需要稍微修正的元素声明内联样式或新类
- ios - Xcode 从旧版本转换为 Swift 4,导致参数标签过载问题
- javascript - 这是回到我原来的提示功能的正确循环吗?(javascript)
- javafx - JavaFX 饼图图例位置在快照上移动
- php - 如何在php中按键读取数组多维
- html-framework-7 - Framework7中是否有“更多选项”(垂直省略号)菜单组件?
- c# - C#如何将CheckBox的字符串值添加到参数中
- python - 类继承错误:子对象没有属性“a”
- go - 为什么在这个例子中我们返回一个指针而不是一个值?
- javascript - 一起使用下划线和不可变