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

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

问题描述

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

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

给出以下父母

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/

推荐答案

在父组件中执行以下操作:

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

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

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天全站免登陆