Home > front end >  ANGULAR - How to disable class usage
ANGULAR - How to disable class usage

Time:10-13

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.

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

Usually, ng-classes are produced by angular and we don't edit them on the runtime.

You can use them in your css files to have the styles that you want. But not put them manually in the HTML.

If you want to validate from string length Angular has a build in validator for that see here.

To disable the input based on validation you can use template variablesand [attr.disabled] directive.

An example:

<input #name [(ngModel)]="name" minlength="1">

<input [(ngModel)]="lastname" [attr.disabled]="!name.valid">

This is not tested code but it should work.

  • Related