【问题标题】:Angular 8: Nested Reactive Form in sub-component not workingAngular 8:子组件中的嵌套反应表单不起作用
【发布时间】: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


    【解决方案1】:

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

    @Input() formGroup: FormGroup;
    

    而不是

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

    于 2020 年 2 月 15 日编辑

    我更改了一些代码并解决了您的问题。解决方案在这里:https://stackblitz.com/edit/angular-vyaj57-kgkdih

    【讨论】:

    • 我已经改变了实现,你的建议也是如此,但我无法在 company.component.html 中显示 companyName。有任何想法吗?我已经用我在 stackblitz 上的解决方案更新了我的问题。
    • 我更新了我的答案并留下了一个包含解决方案的 stackblitz 链接。
    • 亲爱的@bjdose,当我在 app.component.html 的底部添加{{ companies | json }} 输出时,当我开始填充输入框时,输出没有更新。你能解释一下为什么吗?
    【解决方案2】:

    您是否忘记将父 FormGroup 添加到 viewProviders 到您的子组件?像这样:

    @Component({
      selector: 'app-child',
      templateUrl: './child.component.html',
      styleUrls: ['./child.component.less'],
      viewProviders: [
        {
          provide: ParentComponent,
          useExisting: FormGroupDirective
        }
      ]
    })
    

    【讨论】:

    • 是的,我确实忘记添加 viewProviders。什么时候需要这个?你能提供一个用例吗?我已经用我在 stackblitz 上的解决方案更新了我的问题,以遵循 @Brayan 的实施。这是官方/推荐的方式吗?
    • 我仍然无法显示公司名称和地址详细信息。有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 2019-03-27
    • 2020-06-23
    • 2017-07-20
    • 2019-02-01
    • 2020-04-05
    • 2018-07-04
    相关资源
    最近更新 更多