我如何从孩子向父母提交表格

时间:2019-01-19 04:42:44

标签: angular

我想使用一个parentForm,当我单击并保存(两个字段)为空时,它都应显示错误。为什么只在子组件中显示。演示版 https://stackblitz.com/edit/angular-rnophs?file=src%2Fapp%2Fapp.component.ts

2 个答案:

答案 0 :(得分:0)

使用FormGroupDirective代替使用Input属性绑定。在子组件中注入FormGroupDirective将提供对parentForm的访问权限,然后我们可以动态添加表单控件。

尝试一下:

child.component.ts

import { Component, EventEmitter, Input, Output, OnInit } from '@angular/core';
import { FormControl, FormGroup, FormGroupDirective, NgForm, Validators, ControlContainer } from '@angular/forms';

/** @title Input with a custom ErrorStateMatcher */
@Component({
  selector: 'app-child-component',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css'],
  viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }]
})
export class ChildComponent implements OnInit {

  constructor(private fgd: FormGroupDirective) {
  }

  ngOnInit() {
    this.fgd.control.addControl('email', new FormControl())
  }
}

parent.html

<form (ngSubmit)="save()" class="example-form" [formGroup]="parentForm">
  <mat-form-field class="example-full-width">
    <input matInput placeholder="Email" formControlName="emailFormControl">
    <mat-error>
      Please enter a valid email address
    </mat-error>
  </mat-form-field>
  <app-child-component></app-child-component>
  <button type="submit">save</button>
</form>

示例:https://stackblitz.com/edit/angular-7fnwkq

答案 1 :(得分:-1)

您可以在保存方法中使用此表单:

if(this.parentForm.value.emailFormControl){

}
相关问题