【发布时间】:2020-02-14 22:40:20
【问题描述】:
我在子组件中使用 Angular 8 嵌套响应式表单,但它不起作用。我已经搜索了官方 Angular 文档,但找不到任何示例。
我的解决方案可在stackblitz.com 获得。我无法显示每个公司的 companyName 和每个地址的地址详细信息。有什么想法吗?
根据 Kara Ericksons 在 Angular Connect 2017 上谈到“Angular Forms”,它应该是直截了当的......
她在 35:31-36:51 之间的视频Nested Forms in Angular
在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()
}));
}
}
【问题讨论】:
标签: angular angular-reactive-forms