Saurabh Kumar
Saurabh Kumar

Reputation: 16671

Angular 4 control group validation error

I am building a generic form using Angular reactive forms. I have the following generic Html for a input elements

<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>

But for the following !group.controls[config.name]?.errors?.required its telling me Identifier 'required' is not defined . Same for minlength and maxlength. From where i can get minlength and maxlength and required errors?

Upvotes: 1

Views: 940

Answers (2)

developer033
developer033

Reputation: 24894

You can take advantage of the second parameter of AbstractControl#hasError method using it like this:

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

Also, I'd recommend you to use *ngIf instead of hidden.

You can read this for a deep explanation.

Upvotes: 0

Arun Kumaresh
Arun Kumaresh

Reputation: 6311

try this

<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>

Upvotes: 1

Related Questions