如何使用当前的表单API将父组件的FormGroup传递给其子组件

49

我想把父组件的FormGroup传递给它的子组件,以便在子组件中显示错误信息。

假设以下是父组件:

parent.component.ts

import { Component, OnInit } from '@angular/core'
import {
  REACTIVE_FORM_DIRECTIVES, AbstractControl, FormBuilder, FormControl, FormGroup, Validators
} from '@angular/forms'

@Component({
  moduleId: module.id,
  selector: 'parent-cmp',
  templateUrl: 'language.component.html',
  styleUrls: ['language.component.css'],
  directives: [ErrorMessagesComponent]
})
export class ParentCmp implements OnInit {
  form: FormGroup;
  first: AbstractControl;
  second: AbstractControl;
  
  constructor(private _fb: FormBuilder) {
    this.first = new FormControl('');
    this.second = new FormControl('')
  }
  
  ngOnInit() {
    this.form = this._fb.group({
      'first': this.first,
      'second': this.second
    });
  }
}

我现在想把表单: FormGroup 变量传递到下面的子组件中:

error-message.component.ts

import { Component, OnInit, Input } from '@angular/core'
import { NgIf } from '@angular/common'
import {REACTIVE_FORM_DIRECTIVES, FormGroup } from '@angular/forms'

@Component({
  moduleId: module.id,
  selector: 'epimss-error-messages',
  template: `<span class="error" *ngIf="errorMessage !== null">{{errorMessage}}</span>`,
  styles: [],
  directives: [REACTIVE_FORM_DIRECTIVES, NgIf]  
})
export class ErrorMessagesComponent implements OnInit {
  @Input() ctrlName: string

  constructor(private _form: FormGroup) { }

  ngOnInit() { }

  get errorMessage() {
    // Find the control in the Host (Parent) form
    let ctrl = this._form.find(this.ctrlName);
    console.log('ctrl| ', ctrl);

//    for (let propertyName of ctrl.errors) {
//      // If control has a error
//      if (ctrl.errors.hasOwnProperty(propertyName) && ctrl.touched) {
//        // Return the appropriate error message from the Validation Service
//        return CustomValidators.getValidatorErrorMessage(propertyName);
//      }
//    }

    return null;
  }

构造函数 formGroup 表示父级的 FormGroup - 在其当前形式下不起作用。

我试图遵循这个过时的例子:http://iterity.io/2016/05/01/angular/angular-2-forms-and-advanced-custom-validation/


这是另一个想法:https://dev59.com/0Jnga4cB1Zd3GeqPXVkm#38649690 - Paul Samsotha
1
你使用提供的任何答案解决了这个问题吗? - Peter Morris
8个回答

61
在父组件中执行以下操作:
<div [formGroup]="form">
  <div>Your parent controls here</div>
  <your-child-component [formGroup]="form"></your-child-component>
</div>

然后在你的子组件中,你可以像这样获取该引用:

export class YourChildComponent implements OnInit {
  public form: FormGroup;

  // Let Angular inject the control container
  constructor(private controlContainer: ControlContainer) { }

  ngOnInit() {
    // Set our form property to the parent control
    // (i.e. FormGroup) that was passed to us, so that our
    // view can data bind to it
    this.form = <FormGroup>this.controlContainer.control;
  }
}

你甚至可以通过更改组件选择器来确保formGroupName[formGroup]中的任一个都被指定了:
selector: '[formGroup] epimss-error-messages,[formGroupName] epimss-error-messages'

这个答案应该足够满足您的需求,但如果您想了解更多,我在这里写了一篇博客文章:

https://peterlesliemorris.com/angular-how-to-create-composite-controls-that-work-with-formgroup-formgroupname-and-reactiveforms/


4
在 Angular 8 中,this.controlContainer.control as FormGroup 返回以下错误:'类型“AbstractControl”的参数不能分配给类型“FormControl”'。 - Kosmonaft
3
在Angular 8中,我遇到了错误:“Error:“未找到名称为'right'的表单控件值访问器””。 - jebbench
我已经成功在8和9中实现了这个。关键是要确保我有父级[formGroup]标签。 <your-child-component [formGroup]="form"></your-child-component> - Winnemucca
1
很棒的博客文章。真的帮助我将我的表单分解成组件。谢谢。 - GrahamJRoy
2
这仍然有效,但我需要执行 viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }]。如果这不立即起作用,请尝试搜索“useExisting: FormGroupDirective”。 - Simon_Weaver
显示剩余2条评论

13

对于Angular 11,我尝试了所有上述答案,以及不同的组合,但是没有一个完全适合我。所以我最终采用了以下解决方案,它正像我想要的那样运作。

TypeScript

@Component({
  selector: 'fancy-input',
  templateUrl: './fancy-input.component.html',
  styleUrls: ['./fancy-input.component.scss']
})
export class FancyInputComponent implements OnInit {

  valueFormGroup?: FormGroup;
  valueFormControl?: FormControl;

  constructor(
    private formGroupDirective: FormGroupDirective, 
    private formControlNameDirective: FormControlName
  ) {}

  ngOnInit() {
    this.valueFormGroup = this.formGroupDirective.form;
    this.valueFormControl = this.formGroupDirective.getControl(this.formControlNameDirective);
  }

  get controlName() {
    return this.formControlNameDirective.name;
  }

  get enabled() {
    return this.valueFormControl?.enabled
  }

}

HTML

<div *ngIf="valueFormGroup && valueFormControl">
    <!-- Edit -->
    <div *ngIf="enabled; else notEnabled" [formGroup]="valueFormGroup">
        <input class="input" type="text" [formControlName]="controlName">        
    </div>
    <!-- View only -->
    <ng-template #notEnabled>
        <div>
            {{valueFormControl?.value}}
        </div>
    </ng-template>
</div>

用法

请注意,我不得不添加ngDefaultControl,否则它会在控制台中显示默认值访问器错误(如果有人知道如何消除这个错误而不会出错 - 将不胜感激)。

<form [formGroup]="yourFormGroup" (ngSubmit)="save()">
    <fancy-input formControlName="yourFormControlName" ngDefaultControl></fancy-input>
</form>

似乎解决“没有表单控件的值访问器”错误的答案在这里 https://dev59.com/5FcO5IYBdhLWcg3whiBx#45659791,与之相关的是`NG_VALUE_ACCESSOR`。 - Alexander Shagin
1
拥有构造函数参数 private formGroupDirective: FormGroupDirective 真是救了我的一天。 - Harald
我在这里找到了一个方便的替代品:https://medium.com/angular-in-depth/dont-reinvent-the-wheel-when-implementing-controlvalueaccessor-a0ed4ad0fafd - Francesco Cattoni

9
这是一个在父组件 formGroup 中使用的子组件示例: 子组件 ts:
import { Component, OnInit, Input } from '@angular/core';
import { FormGroup, ControlContainer, FormControl } from '@angular/forms';


@Component({
  selector: 'app-date-picker',
  template: `
  <mat-form-field [formGroup]="form" style="width:100%;">
  <input matInput [matDatepicker]="picker" [placeholder]="placeHolder" [formControl]="control" readonly>
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>
<mat-icon (click)="clearDate()">replay</mat-icon>`,
  styleUrls: ['./date-picker.component.scss']
})

export class DatePickerComponent implements OnInit {
  public form: FormGroup;
  public control : FormControl;
  @Input() controlName : string;
  @Input() placeHolder : string;


  constructor(private controlContainer: ControlContainer) { 
  }

  clearDate(){
    this.control.reset();
  }

  ngOnInit() {
    this.form = <FormGroup>this.controlContainer.control;
    this.control = <FormControl>this.form.get(this.controlName);
    }

}

CSS日期选择器:

mat-icon{
position: absolute;
left: 83%;
top: 31%;
transform: scale(0.9);
cursor: pointer;
}

并且可以这样使用:
 <app-date-picker class="col-md-4" [formGroup]="feuilleForm" controlName="dateCreation" placeHolder="Date de création"></app-date-picker>

9

父组件:

    @Component({
      selector: 'app-arent',
      templateUrl: `<form [formGroup]="parentFormGroup" #formDir="ngForm">
                       <app-child [formGroup]="parentFormGroup"></app-child>
                    </form>         `
    })
    
    export class ParentComponent implements {
        
     parentFormGroup :formGroup
    
     ngOnChanges() {        
       console.log(this.parentFormGroup.value['name'])
     }
  }

子组件:

    @Component({
      selector: 'app-Child',
      templateUrl: `<form [formGroup]="childFormGroup" #formDir="ngForm">
                        <input id="nameTxt" formControlName="name">
                    </form>         `
    })
    
    export class ChildComponent implements OnInit {
     @Input()  formGroup: FormGroup
    
     childFormGroup :FormGroup
    
    ngOnInit() {
      // Build your child from
      this.childFormGroup.addControl('name', new FormControl(''))
    
      /* Bind your child form control to parent form group
         changes in 'nameTxt' directly reflect to your parent 
         component formGroup
        */          
     this.formGroup.addControl("name", this.childFormGroup.controls.name);
   
     }
  }

我可以问一下,在两个组件中的 #formDir="ngForm" 是否与将父表单传递给子表单的工作有关吗? - Mike
1
不,两个组件都有自己的 #formDir="ngForm",它们彼此之间没有关联。 - Surendranath Sonawane

3
我会这样做,我已将子表单数据作为组传递给父级,因此您可以在提交调用中拥有分离的表单数据。 父级:
<form [formGroup]="registerStudentForm" (ngSubmit)="onSubmit()">
<app-basic-info [breakpoint]="breakpoint" [formGroup]="registerStudentForm"></app-basic-info>
<button mat-button>Submit</button>
</form>

孩子:

<mat-card [formGroup]="basicInfo">
    <mat-card-title>Basic Information</mat-card-title>
    <mat-card-content>
      <mat-grid-list
        [gutterSize]="'20px'"
        [cols]="breakpoint"
        rowHeight="60px"
      >
        <mat-grid-tile>
          <mat-form-field appearance="legacy" class="full-width-field">
            <mat-label>Full name</mat-label>
            <input matInput formControlName="full_name" />
          </mat-form-field>
        </mat-grid-tile>
    </mat-grid-list>
</mat-card-content>
</mat-card>

Parent.ts:

export class RegisterComponent implements OnInit {
    constructor() { }

    registerForm = new FormGroup({});
  
    onSubmit() {
      console.warn(this.registerForm.value);
    }
  
  }

Child.ts

export class BasicInfoComponent implements OnInit {
  @Input() breakpoint;
  @Input() formGroup: FormGroup;
  basicInfo: FormGroup;
  constructor() { }

  ngOnInit(): void {
    this.basicInfo = new FormGroup({
      full_name: new FormControl('Riki maru'),
      dob: new FormControl(''),
    });
    this.formGroup.addControl('basicInfo', this.basicInfo);
  }
}

在您的子组件中,@Input() formGroup: FormGroup;部分将是父组件的引用


2

ngOnInit 很重要 - 这在构造函数中无法工作。 我更喜欢查找 FormControlDirective - 它是在子组件祖先层次结构中找到的第一个。

constructor(private formGroupDirective: FormGroupDirective) {}

  ngOnInit() {
    this.formGroupDirective.control.addControl('password', this.newPasswordControl);
    this.formGroupDirective.control.addControl('confirmPassword', this.confirmPasswordControl);
    this.formGroup = this.formGroupDirective.control;
  }

0
我会将表单作为输入传递给子组件;
@Component(
    {
      moduleId: module.id,
      selector: 'epimss-error-messages',
      template: `
   <span class="error" *ngIf="errorMessage !== null">{{errorMessage}}</span>`,
      styles: [],
      directives: [REACTIVE_FORM_DIRECTIVES, NgIf]

    })
export class ErrorMessagesComponent implements OnInit {
  @Input()
  ctrlName: string

  @Input('form') _form;

  ngOnInit() {
         this.errorMessage();
      }

  errorMessage() {
    // Find the control in the Host (Parent) form
    let ctrl = this._form.find(this.ctrlName);

    console.log('ctrl| ', ctrl)

//    for (let propertyName of ctrl.errors) {
//      // If control has a error
//      if (ctrl.errors.hasOwnProperty(propertyName) && ctrl.touched) {
//        // Return the appropriate error message from the Validation Service
//        return CustomValidators.getValidatorErrorMessage(propertyName);
//      }
//    }

    return null;
  }

当然,您需要将表单从父组件传递给子组件,可以通过不同的方式实现,但最简单的方法是:
在父组件中的某个位置;
     <epimss-error-messages [form]='form'></epimss-error-messages>

3
我认为构造函数参数列表中的 private _form: FormGroup) 应该被移除。 - Günter Zöchbauer

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接