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

yc0p9oo0  于 2023-05-12  发布在  Java
关注(0)|答案(8)|浏览(139)

我想将父组件的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
    });
  }
}

我现在想把上面的form: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/上遵循这个过时的示例

9rbhqvlz

9rbhqvlz1#

在父零部件中执行以下操作:

<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/

qyuhtwio

qyuhtwio2#

对于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,否则它将在控制台中给予默认值accessor error(如果有人知道如何在没有错误的情况下摆脱它-将非常感谢)。

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

vxf3dgd43#

这是在父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>
ffscu2ro

ffscu2ro4#

父组件:

@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);
   
     }
  }
klr1opcd

klr1opcd5#

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;
  }
yks3o0rb

yks3o0rb6#

我会这样做,我已经通过子窗体数据作为一组父,所以你可以在提交调用分离的表单数据。

父级:

<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>

父级.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;部分将是父组件的引用

cedebl8k

cedebl8k7#

我将表单作为输入传递给子组件;

@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>
wvt8vs2t

wvt8vs2t8#

如果要从子组件访问父组件,可以访问FormControl示例的parent属性https://angular.io/api/forms/AbstractControl#parent
要获取父错误,请执行以下操作:

const parent = control.parent;
const errors = parent.errors;

相关问题