首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用当前表单API将父组件的FormGroup传递给其子组件

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

Stack Overflow用户
提问于 2016-07-23 23:45:15
回答 8查看 73K关注 0票数 38

我希望将父组件的FormGroup传递给其子组件,以便使用子组件显示错误消息。

鉴于以下父母:

parent.component.ts

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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/学习这个过时的例子

EN

回答 8

Stack Overflow用户

发布于 2017-08-10 21:04:18

在父组件中这样做:

代码语言:javascript
运行
复制
<div [formGroup]="form">
  <div>Your parent controls here</div>
  <your-child-component [formGroup]="form"></your-child-component>
</div>

然后,在您的子组件中,您可以获得如下所示的引用:

代码语言:javascript
运行
复制
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]

代码语言:javascript
运行
复制
selector: '[formGroup] epimss-error-messages,[formGroupName] epimss-error-messages'

这个答案应该足以满足你的需要,但是如果你想知道更多,我在这里写了一个博客:

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

票数 50
EN

Stack Overflow用户

发布于 2021-04-06 01:57:42

对于角度11,我尝试了以上所有的答案,并以不同的组合,但没有什么对我很有效。因此,我最终得到了如下的解决方案,这对我来说就像我想要的那样。

TypeScript

代码语言:javascript
运行
复制
@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

代码语言:javascript
运行
复制
<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,否则它将不会在控制台中给出默认值访问器错误(如果有人知道如何在没有错误的情况下消除它,我们将不胜感激)。

代码语言:javascript
运行
复制
<form [formGroup]="yourFormGroup" (ngSubmit)="save()">
    <fancy-input formControlName="yourFormControlName" ngDefaultControl></fancy-input>
</form>
票数 10
EN

Stack Overflow用户

发布于 2019-02-21 10:15:22

这是父formGroup内部使用的子组件示例:子组件ts:

代码语言:javascript
运行
复制
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日期选择器:

代码语言:javascript
运行
复制
mat-icon{
position: absolute;
left: 83%;
top: 31%;
transform: scale(0.9);
cursor: pointer;
}

像这样使用:

代码语言:javascript
运行
复制
 <app-date-picker class="col-md-4" [formGroup]="feuilleForm" controlName="dateCreation" placeHolder="Date de création"></app-date-picker>
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38547389

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档