Angular Material ErrorStateMatcher 能否检测到父表单何时提交?

Can the Angular Material ErrorStateMatcher detect when a parent form is submitted?

我有一个设置表单并将其传递给子组件的父组件。

<form [formGroup]="form" (submit)="submit()">
  <app-child [form]="form"></app-child>
  <button mat-button type="submit">Submit</button>
</form>

子组件显示这样的输入字段:

<mat-form-field *ngIf="form" [formGroup]="form">
  <input matInput
         placeholder="Email"
         formControlName="email"
         [errorStateMatcher]="matcher"
         required>
</mat-form-field>

输入字段是必需的,如果在没有填写表单的情况下提交表单,即使用户从未触摸过它,也应显示错误。这是一种简单形式的自动行为,但是(我认为)因为我使用的是子形式,所以我必须使用 ErrorStateMatcher.

实现自定义错误逻辑
export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control, form) {
    return control && control.invalid && form && form.submitted;
  }
}

但是,这不起作用。我不知道如何让子输入检测父表单何时提交。 ErrorStateMatcher 检测到某些内容已更改,但 formsubmitted 属性 始终是 false。我做错了什么?

See this Stackblitz

您无需实施 ErrorStateMatcher 即可实现此类行为。在 mat-form-field

上使用 formGroup 没有意义

只需更改child.component.html如下

<mat-form-field *ngIf="form">
  <input matInput placeholder="Email" [formControl]="form.get('email')">
</mat-form-field>

这是一个工作示例https://stackblitz.com/edit/angular-material-error-matcher-child-component-6nwmwe