【问题标题】:Passing form status data between parent and child components在父组件和子组件之间传递表单状态数据
【发布时间】:2017-03-14 18:59:58
【问题描述】:

使用 Angular 2,我有一个长而复杂的表单,我将其拆分为一个父组件和两个子组件,以便于管理。在我需要跟踪表单状态以进行验证之前,该过程非常有效。虽然可以通过@Input 轻松传输有关绑定模型的数据,但我不知道如何传输有关表单本身的数据。

这是一个使用伪代码的示例:

@Component({
    template: `
        <form #f="ngForm">
          <basic-details [exampleModel]="exampleModel"></basic-details>
          <advanced-details [exampleModel]="exampleModel"></advanced-details>
          <p>Form data: {{f.value | json}}</p>
        </form>
    `
})
export class ParentFormComponent {
    public exampleModel: ExampleModel = new ExampleModel();
}

@Component({
    selector: 'basic-details',
    template: `
        <input type="text" name="details" [(ngModel)]="exampleModel.details">
    `
})
export class BasicDetailsComponent {
    @Input() exampleModel: ExampleModel;
}

@Component({
    selector: 'advanced-details',
    template: `
        <input type="text" name="advanced" [(ngModel)]="exampleModel.advanced">
    `
})
export class AdvancedDetailsComponent {
    @Input() exampleModel: ExampleModel;
}

在表单的底部,我使用 JSON 管道显示表单值。 f.value 应该显示有关“详细信息”和“高级”输入的数据。如何在父组件和子组件之间传递信息,以便父​​组件可以跟踪表单状态?理想情况下,这适用于模板驱动和反应式表单。

【问题讨论】:

  • 标准方式是将数据存储在所有组件都可以访问的服务中。

标签: angular angular2-forms angular2-formbuilder


【解决方案1】:

正如 John 所提到的,创建一个父子组件共享的服务是一个很好的解决方案。然后您可以使用FormArray 来判断所有表单是否有效。

服务示例:

import { Injectable } from '@angular/core';
import { FormArray, FormGroup } from '@angular/forms';

@Injectable()
export class FormService {
  private formArray: FormArray = new FormArray([]);

  addForm(formGroup: FormGroup) {
    this.formArray.push(formGroup);
  }

  allValid(): boolean {
    return this.formArray.valid;
  }

  anyDirty(): boolean {
    return this.formArray.dirty;
  }
}

在您的 ParentComponent 中,您希望提供服务,以便仅在父组件和其子组件之间共享。

@Component({
  ...
  providers: [FormService]
})

在您的组件中,您需要在构建表单后调用this.formservice.addForm(this.form);

【讨论】:

    猜你喜欢
    • 2020-10-26
    • 2017-09-04
    • 2017-10-24
    • 2020-07-08
    • 2019-02-17
    • 2019-04-02
    • 2021-06-30
    • 2018-01-02
    • 2017-08-26
    相关资源
    最近更新 更多