首页 > 解决方案 > 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()

    }));
  }
}

标签: angularangular-reactive-forms

解决方案


尝试将您的 formGroup 作为输入而不是使用构造函数传递给子组件。

@Input() formGroup: FormGroup;

代替

constructor(parent: FormGroupDirective) {
  this.form = parent.form;
}

2020 年 2 月 15 日已编辑

我更改了一些代码并解决了您的问题。该解决方案可在此处获得:https ://stackblitz.com/edit/angular-vyaj57-kgkdih


推荐阅读