Angular 反应式嵌套表单

Angular reactive nested forms

我试图在我的 angular 项目中嵌套多个响应式表单,并且表单位于不同的组件中。

例如,我有一个组件,其中包含一个表单,该表单有两个输入,一个输入名称,一个输入描述,还有一个提交按钮。我称这个组件为 NameDescComponent

我计划在多个页面和表单中使用此组件。这是组件的 html。

<form [formGroup]="nameDescForm" (ngSubmit)="customEmit()">
    <div fxLayout="row" fxLayoutGap="10px" fxFlex>
      <mat-form-field>
        <input matInput placeholder="Name" formControlName="name">
      </mat-form-field>
      <mat-form-field fxFlex>
        <input matInput placeholder="Description" formControlName="description">
      </mat-form-field>
    </div>
    <div fxLayout="column" fxLayoutGap="10px">
      <button type="submit" mat-raised-button color="primary">
        {{buttonText}}
      </button>
      <div>
      </div>
    </div>
  </form>

这里是缩写的ts文件

public nameDescForm: FormGroup;



@Input() public buttonText: string;
  @Output() public save: EventEmitter<any> = new EventEmitter<any>();
  @Output() public nameDescFormEmit: EventEmitter<FormGroup> = new EventEmitter<FormGroup>();

  constructor(fb: FormBuilder) {
    this.nameDescForm = fb.group({
      'name': ['', Validators.required],
      'description': ['']
    });
  }

  public ngOnInit() {
    console.log(this.nameDescForm);
    this.nameDescFormEmit.emit(this.nameDescForm);
  }

  public customEmit() {
    this.save.emit();
  }

然后在我使用此组件的页面中,我还有另一个表单,其中包含 NameDescComponent,如下所示

<form [formGroup]="parentForm" (ngSubmit)="customEmit()">

  <app-name-description (nameDescFormEmit)="getNameDescForm($event)" buttonText="Save" (save)="save()"></app-name-description>

  <input type="test" formControlName="test">

</form>

目前我正在做的是将 nameDescFrom 从其组件传递到带有输出和事件发射器的 ParentComponent。此解决方案似乎有效,当我更新 child 时,我能够访问这些值。但不利的是,当我去提交表格时,我必须检查 parentFormnameDescFrom 是否都有效并分别管理这两个表格。

我想知道是否有更好的方法来解决这个问题?我何时可以从 parent 表单中访问 nameDescFrom

谢谢

要将您的表单与嵌套表单合并并对所有表单进行单一验证过程,您可以使用 formbuilder 在根表单组件中创建整个模型对象结构。 然后在其 html 模板中添加子表单的自定义元素(例如:<nested-form>),这将呈现子表单。

参见示例:https://stackblitz.com/edit/angular-m5fexe)

有用的 angular 文档链接:

代码:

export class Form1Component  {
  @Input() name: string;

  public dummyForm: FormGroup;

  constructor(
      private _fb: FormBuilder,
  ) {
      this.createForm();
  }

  createForm() {
    this.dummyForm = this._fb.group({
      username: ['username', Validators.required],
      nestedForm: this._fb.group({        
        complement1: ['complement1', Validators.required],
        complement2: ['complement2', Validators.required],
      })
    });
  }

  submit() {
    if (this.dummyForm.valid) {
      console.log('form AND subforms are valid', this.dummyForm.value);
    } else {
      console.warn('form AND/OR subforms are invalid', this.dummyForm.value);
    }
  }
}

Form1Component 的模板:

<form [formGroup]="dummyForm" (ngSubmit)="submit()">    
    <div>
      <label for="username">Root Input</label>
      <input type="text" id="username" formControlName="username"/>
    </div>
    <nested-form [parentForm]="dummyForm"></nested-form>
    <button>Send</button>    
  </form>

嵌套表单代码:

export class NestedFormComponent {
  @Input()
  public parentForm: FormGroup;
}

嵌套表单模板:

<form [formGroup]="parentForm">
    <div formGroupName="nestedForm">
      <div>
        <label for="complement1">Nested input 1</label>
        <input type="text" formControlName="complement1"/>
      </div>
      <div>
        <label for="complement1">Nested input 1</label>
        <input type="text" formControlName="complement2"/>
      </div>
    </div>
  </form>

您还可以使用自定义表单控件,它是 angular 中的一个内置概念。

我们的想法是拥有一个自定义组件,作为父表单和嵌套表单之间的“桥梁”。自定义组件将监听嵌套表单的“更改”事件,并使用它更新它的值。父表单将自定义控件视为单个字段,尽管其值将是包含嵌套表单控件值的对象。

自定义组件应实现一个名为 ControlValueAccessor 的接口,通过该接口 angular 提供更新自定义控件状态(如值、有效、触摸、原始等)所需的一切。通过这种方式,您实际上管理了自定义控件状态,以便父窗体可以像对待任何其他窗体控件一样对待它。

您可以在以下链接中了解它:

https://blog.sreyaj.dev/custom-form-controls-controlvalueaccessor-in-angular

https://medium.com/@majdasab/implementing-control-value-accessor-in-angular-1b89f2f84ebf

https://indepth.dev/posts/1055/never-again-be-confused-when-implementing-controlvalueaccessor-in-angular-forms