angular - Angular 8:子组件中的嵌套反应表单不起作用
问题描述
我在子组件中使用 Angular 8 Nested Reactive Form,但它不起作用。我已经搜索了官方 Angular 文档,但我找不到任何关于此的示例。
我的解决方案可在stackblitz.com上找到。我无法显示每个公司的 companyName 和每个地址的地址详细信息。有任何想法吗?
根据Kara Ericksons 在 Angular Connect 2017 上谈论“Angular Forms”的说法,它应该是直截了当的......
她的视频嵌套表单在35:31-36:51 之间
在parent.component.html
<form [formGroup]="form">
<div *ngFor="let address of addresses">
<app-child [address]="address"></app-child>
</div>
<button type="submit">Save</button>
</form>
在parent.component.ts
export class ParentComponent implements OnInit {
form = new FormGroup({});
addresses : Address[] = [
new Address("Street 1", "City 1"),
new Address("Street 2", "City 2"),
new Address("Street 3", "City 3"),
]
constructor() { }
ngOnInit() {
}
}
在child.component.html
<div formGroupName="address">
<input formControlName="street">
<input formControlName="city">
</div>
在child.component.ts
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.less']
})
export class ChildComponent implements OnInit {
@Input() address: Address;
form: FormGroup;
constructor(parent: FormGroupDirective) {
this.form = parent.form;
}
ngOnInit() {
this.form.addControl('address', new FormGroup({
street: new FormControl()
city: new FormControl()
}));
}
}
解决方案
尝试将您的 formGroup 作为输入而不是使用构造函数传递给子组件。
@Input() formGroup: FormGroup;
代替
constructor(parent: FormGroupDirective) {
this.form = parent.form;
}
2020 年 2 月 15 日已编辑
我更改了一些代码并解决了您的问题。该解决方案可在此处获得:https ://stackblitz.com/edit/angular-vyaj57-kgkdih
推荐阅读
- azure-devops - 在满足指定要求的池中找不到代理:npm,Agent.Version
- typescript - 从库依赖项创建单例
- mysql - 在没有权限的情况下查询 MySQL db 不会导致 COMMAND denied to user (Express js)
- python - 我的脚本有效,但出现了这个警告,我不知道这是什么意思,这个comport是什么
- node.js - 我如何通过另一个在 Sequelize 中具有一对一关系的表来关联两个表
- python - 为什么python无法连接到代理?
- javascript - Kendo PDF 无法正确拆分页面
- javascript - res.json 中的相同对象
- django - Django 的 ManyToManyField 和 ManyToManyRel 的区别
- python - 如何在烧瓶中使用来自 sqlite3 的用户布尔值