Angular 4 控制组验证错误

Angular 4 control group validation error

我正在使用 Angular 响应式表单构建通用表单。我有以下通用 Html 作为输入元素

<div class="form-input form-group" [formGroup]="group">
    <div class="row">
        <div class="col-2 font-label">
            <label>{{ config.label }}</label>
        </div>
        <div class="col-10">
            <input type="text" [attr.placeholder]="config.placeholder" disabled="disabled" class="form-control"
                [formControlName]="config.name">
            <div [hidden]="!(group.controls[config.name].invalid && group.controls[config.name].touched)">
                <small class="form-text text-danger" [hidden]="!group.controls[config.name]?.errors?.required"></small>
                <small class="form-text text-danger" [hidden]="!group.controls[config.name]?.errors?.minlength"></small>
                <small class="form-text text-danger" [hidden]="!group.controls[config.name]?.errors?.maxlength"></small>
            </div>
        </div>
    </div>
</div>

但对于以下 !group.controls[config.name]?.errors?.required 它告诉我 Identifier 'required' is not definedminlengthmaxlength 相同。从哪里可以得到 minlengthmaxlength 以及 required errors?

试试这个

<small class="form-text text-danger" [hidden]="!group.controls[config.name].hasError('required')"></small>
<small class="form-text text-danger" [hidden]="!group.controls[config.name].hasError('minlength')"></small>
<small class="form-text text-danger" [hidden]="!group.controls[config.name].hasError('maxlength')"></small>

您可以像这样使用 AbstractControl#hasError 方法的第二个参数:

<small class="form-text text-danger" 
       [hidden]="!group.hasError('required', config.name)">
</small>

此外,我建议您使用 *ngIf 而不是 hidden

You can read this for a deep explanation.