如何使用当前的 Form API 将父组件的 FormGroup 传递给其子组件 [英] How can I pass the FormGroup of a parent component to its child component using the current Form API

查看:26
本文介绍了如何使用当前的 Form API 将父组件的 FormGroup 传递给其子组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将父组件的 FormGroup 传递给它的子组件,以便使用子组件显示错误消息.

给定以下父级:

parent.component.ts

import { Component, OnInit } from '@angular/core'进口 {REACTIVE_FORM_DIRECTIVES、AbstractControl、FormBuilder、FormControl、FormGroup、验证器来自'@angular/forms'@成分({模块 ID:module.id,选择器:'parent-cmp',templateUrl: 'language.component.html',styleUrls: ['language.component.css'],指令:[ErrorMessagesComponent]})导出类 ParentCmp 实现 OnInit {表格:表格组;第一个:抽象控件;第二个:抽象控件;构造函数(私有_fb:FormBuilder){this.first = new FormControl('');this.second = new FormControl('')}ngOnInit() {this.form = this._fb.group({'第一':this.first,'第二':this.second});}}

我现在想将上面的 form:FormGroup 变量传递给下面的子组件:

error-message.component.ts

import { Component, OnInit, Input } from '@angular/core'从@angular/common"导入 { NgIf }从@angular/forms"导入 {REACTIVE_FORM_DIRECTIVES, FormGroup }@成分({模块 ID:module.id,选择器:'epimss-错误-消息',模板:`<span class="error";*ngIf="errorMessage !== null">{{errorMessage}}</span>`,样式:[],指令:[REACTIVE_FORM_DIRECTIVES, NgIf]})导出类 ErrorMessagesComponent 实现 OnInit {@Input() ctrlName: 字符串构造函数(私有_form:FormGroup){}ngOnInit() { }获取错误消息(){//在Host(Parent)窗体中找到控件让 ctrl = this._form.find(this.ctrlName);console.log('ctrl|', ctrl);//for (let propertyName of ctrl.errors) {////如果控件有错误//if (ctrl.errors.hasOwnProperty(propertyName) && ctrl.touched) {////从验证服务返回适当的错误消息//返回 CustomValidators.getValidatorErrorMessage(propertyName);//}//}返回空;}

构造函数 formGroup 表示父级的 FormGroup - 在当前形式中它不起作用.

我试图在 http://iterity.io/2016/05/01/angular/angular-2-forms-and-advanced-custom-validation/

解决方案

在父组件中这样做:

<div>您的父级控件在此处</div><your-child-component [formGroup]="form"></your-child-component>

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

导出类 YourChildComponent 实现 OnInit {公共表单:FormGroup;//让 Angular 注入控件容器构造函数(私有控制容器:ControlContainer){}ngOnInit() {//将我们的表单属性设置为父控件//(即FormGroup)传递给我们,以便我们的//视图可以将数据绑定到它this.form = <FormGroup>this.controlContainer.control;}}

您甚至可以通过像这样更改其选择器来确保在您的组件上指定了 formGroupName[formGroup]:

selector: '[formGroup] epimss-error-messages,[formGroupName] epimss-error-messages'

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

https://mrpmorris.blogspot.co.uk/2017/08/angular-composite-controls-formgroup-formgroupname-reactiveforms.html

I would like to pass the parent component's FormGroup to its child for the purpose of displaying an error-message using the child.

Given the following parent:

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

I would now like to pass the form:FormGroup variable above to the child component below:

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

The constructor formGroup represents the FormGroup of the parent - in its present form it does not work.

I am trying to follow this obsolete example at http://iterity.io/2016/05/01/angular/angular-2-forms-and-advanced-custom-validation/

解决方案

In the parent component do this:

<div [formGroup]="form">
  <div>Your parent controls here</div>
  <your-child-component [formGroup]="form"></your-child-component>
</div>

And then in your child component you can get hold of that reference like so:

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

You can even ensure either formGroupName or [formGroup] is specified on your component by changing its selector like so:

selector: '[formGroup] epimss-error-messages,[formGroupName] epimss-error-messages'

This answer should be sufficient for your needs, but if you want to know more I've written a blog entry here:

https://mrpmorris.blogspot.co.uk/2017/08/angular-composite-controls-formgroup-formgroupname-reactiveforms.html

这篇关于如何使用当前的 Form API 将父组件的 FormGroup 传递给其子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆