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?
CodePudding user response:
You can try [ngClass] attribute directive for same, Please see below the code how to do that:-
<div style="margin-right: 2rem; display: flex;">
<textarea pInputText [ngClass]="{'ng-invalid ng-dirty':commentText.length===0}" [(ngModel)]="commentText" style="width: 100%;" rows="3" cols="50" pInputTextarea [autoResize]="false"></textarea>
</div>
CodePudding user response:
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>