Search code examples
angularangular-forms

How to validate form element without using reactive forms?


I want to validate an element without using Reactive Forms, I am using two way binding like below:

 <input
                    type="text"
                    class="form-control"
                    autocomplete="off"
                    [required]="fieldDefinition.required"
                    [disabled]="fieldDefinition.disabled"
                    [(ngModel)]="fieldDefinition.fieldvalue"
                />

How to highlight elements by red color after clicking on a button if they are required? So, I need to validate all fields after button click.


Solution

  • Angular add the class ng-invalid ng-touched to the inputs with [(ngModel)] -also if you use ReactiveForms

    so, you can declare a variable

    submitted=false;
    

    And in button

    <button (click)="submitted=true">submit</button>
    

    Your inputs add the class submitted when the variable becomes true

    <input [class.submitted]="submitted" ....>
    

    And you can define a .css like

    .submitted.ng-invalid
    {
      border-color:red
    }
    

    You can see a simple example in this stackblitz