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

问题描述 投票:0回答:1

我有一个子组件调用app-account包含一个提交表单,其中包含一些像这样的输入字段验证器

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>

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

<app-account></app-account>

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

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

我该怎么解决呢,谢谢!

angular
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.