如何在不单击或触摸 Angular 的情况下验证父组件中的子组件



我有一个子组件调用应用程序帐户,其中包含一个提交表单,其中包含一些输入字段验证器,如下所示

this.user = this.fb.group({
usrname: new FormControl('', Validators.compose([Validators.required])),
password: new FormControl('', Validators.compose([Validators.required, Validators.minLength(6)]))});

和在 HTML 模板中

<form [formGroup]="user" (ngSubmit)="onSubmit()">
<mat-form-field>
<input matInput placeholder="Account" formControlName="usrname">
<mat-error *ngIf="!!user.controls.usrname.errors?.required">{{usrrequire_msg}}
</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput type="password" placeholder="Password" formControlName="password">
<mat-error *ngIf="!!user.controls.password.errors?.required">
{{pwrequire_qmsg}}
</mat-error>
<mat-error *ngIf="!!user.controls.password.hasError('minlength')">
{{pwminimum_msg}}
</mat-error>
</mat-form-field>

我像子组件一样将这个组件嵌入到父组件 HTML 中

<app-account></app-account>

在父组件中,我有一个提交按钮

布局加载正常,但是当我单击父组件中的提交按钮并单击或触摸到子输入字段时 => 没有任何错误验证消息显示?

我该如何解决它,谢谢!

只需使用 [formControl].markAsTouch(( 和 [formControl] 就是来自子组件的表单控件...此方法将执行类似使用触摸或单击此字段的操作。然后显示验证消息。

相关内容

最新更新