[英]Can the Angular Material ErrorStateMatcher detect when a parent form is submitted?
I have a parent component that sets up a form and passes it down to a child component. 我有一个父组件,它可以设置表单并将其传递给子组件。
<form [formGroup]="form" (submit)="submit()">
<app-child [form]="form"></app-child>
<button mat-button type="submit">Submit</button>
</form>
The child component displays an input field like this: 子组件显示如下输入字段:
<mat-form-field *ngIf="form" [formGroup]="form">
<input matInput
placeholder="Email"
formControlName="email"
[errorStateMatcher]="matcher"
required>
</mat-form-field>
The input field is required and should show an error if the form is submitted without filling it in, even if the user never touched it. 输入字段是必填字段,并且如果提交表单时未填写该表单,即使用户从未触摸过,也应显示错误。 This is the automatic behavior in a simple form, but (I think) since I am using a child form, I have to implement custom error logic with ErrorStateMatcher
. 这是一种简单形式的自动行为,但是(我认为)因为我使用的是子表单,所以我必须使用ErrorStateMatcher
实现自定义错误逻辑。
export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control, form) {
return control && control.invalid && form && form.submitted;
}
}
However, this doesn't work. 但是,这不起作用。 I can't figure out how to get the child input to detect when the parent form has been submitted. 我不知道如何获取子输入以检测何时提交了父表单。 The ErrorStateMatcher
detects that something has changed, but the submitted
property of form
is always false
. ErrorStateMatcher
检测到某些更改,但是form
的submitted
属性始终为false
。 What am I doing wrong? 我究竟做错了什么?
you don't need to implement ErrorStateMatcher
to achieve such behavior. 您无需实现ErrorStateMatcher
即可实现这种行为。 and it doesn't make sense to use formGroup
on a mat-form-field
而且在mat-form-field
上使用formGroup
意义
Just change child.component.html
as follows 只需如下更改child.component.html
<mat-form-field *ngIf="form">
<input matInput placeholder="Email" [formControl]="form.get('email')">
</mat-form-field>
here is a working example https://stackblitz.com/edit/angular-material-error-matcher-child-component-6nwmwe 这是一个工作示例https://stackblitz.com/edit/angular-material-error-matcher-child-component-6nwmwe
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.