子组件中的Angular反应形式提交

时间:2020-10-11 18:43:26

标签: angular angular-material

我已经建立了一个简单的项目来解释我的问题。我有一个主要组件,用于定义具有三个字段的表单。第三个字段在子组件中定义。

我简化了将formGroup传递给子组件以绑定值的过程。从数据绑定的角度来看,它一切都很好,但是当我单击表单的“提交”时,我可以看到对父组件中定义的字段进行验证,但是子组件中的组件没有变成红色

项目示例:https://stackblitz.com/edit/angular-74rac8 点击提交

我如何告诉孩子表格已经提交?我以为是这样,因为我传递了相同的formGroup对象

1 个答案:

答案 0 :(得分:3)

所有Angular材质表单控件在更新错误状态时都使用相同的逻辑:

@Injectable({providedIn: 'root'})
export class ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    return !!(control && control.invalid && (control.touched || (form && form.submitted)));
  }
}

这意味着要使控件变成红色,它应该具有无效的状态(正常运行),但也应该被触摸或提交父FormGroupDirective。

您有两个FormGroupDirective,并且仅提交了根指令((在<form [formGroup]="layerFormGroup"元素上定义)。未提交子FormGroupDirective(<div [formGroup]="formReference">),因此控件没有变成红色。

请注意,如果您触摸子级mat-select,它也会被标记为无效。

为了解决该问题,您可以跳过将FormGroup传递给子组件,而是告诉Angular您将对子组件使用相同的父FormGroupDirective:

child.component.ts

import { FormGroupDirective, ControlContainer } from '@angular/forms';

@Component({
  selector: 'app-child',
  ...
  viewProviders: [
    {
      provide: ControlContainer,
      useExisting: FormGroupDirective
    }
  ]
}) 
export class ChildComponent implements OnInit  {

Forked Stackblitz