[FIXED] ANGULAR – How to disable class usage (Validation problem)

Issue

I’m using a class from the PrimeNG collection of UI components for Angular. The class combination ng-invalid ng-dirty is used for displaying the validation errors.

.ts

export class LocationVisitComponent implements OnInit {
  commentText: string = '';
}

.html

<div style="margin-right: 2rem; display: flex;">
        <textarea pInputText class="ng-invalid ng-dirty" [(ngModel)]="commentText" style="width: 100%;" rows="3" cols="50" pInputTextarea [autoResize]="false"></textarea> 
</div>

When the class is specified, the border of the text area is painted in red. I want to check if text area length is greater than one and if it is, I need to disable a class.
What is the best solution to this problem?

Solution

I resolved this problem with Angular Reactive Forms. Now, I can use PrimeNG components and validations.

.ts

import { FormGroup, FormControl } from '@angular/forms';

export class LocationVisitComponent implements OnInit {
  visitForm: FormGroup;

  ngOnInit(): void {
    this.visitForm=new FormGroup({
      textArea: new FormControl('')
    });
  }

  startVisit():void {
    alert('Submit');
  }
}

.html

<form novalidate (ngSubmit)="startVisit()" [formGroup]="visitForm">
    <textarea pInputText id="textAreaId" placeholder="Comment (required)" rows="3" cols="50"
    pInputTextarea [autoResize]="false" required minlength="15" formControlName="textArea"
    [ngClass]="{'ng-invalid ng-dirty' : (visitForm.get('textArea').touched || visitForm.get('textArea').dirty) && !visitForm.get('textArea').valid }"
    ></textarea>

    <div>
        <p-button type="submit"
            [title]="visitForm.valid ? 'Save your entered data' : 'Disabled until the form data is valid'"
            [disabled]="!visitForm.valid">
            Start
        </p-button>
    </div>
</form>

Answered By – Domagoj Hamzic

Answer Checked By – Marilyn (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published