0

I am new to angular 4 ,Here I am trying to implement angular form validation messages in my application .

Here the validation message is get displayed as expected but the text field and label color is not get changed based on the state.

HTML :

<form #AddressForm="ngForm" (ngSubmit)="SaveAddress(mAddress_Model)">
   <div class="form-group" [class.has-error]="Name.invalid && Name.touched" [class.has-success]="Name.valid">
   <label for="FName" class="control-label" >First Name *</label>
   <input type="text" required minlength="4" id="Name" name="Name" class="form-control "  [(ngModel)]="mAddress_Model.mFName"  #Name="ngModel">
    <div class="help-block alert-danger col-sm-12" *ngIf="Name.errors.required && Name.touched">
                    * First name is required
    </div>
  </div>
</form>

Here **[class.has-error]="Name.invalid && Name.touched" [class.has-success]="Name.valid"** not worked for me but the validation message div is working .

I followed this blog http://csharp-video-tutorials.blogspot.com/2018/01/displaying-angular-form-validation.html

Can anyone help me to solve this .

6
  • 2
    Please provide a minimal reproducible example. Commented Jul 23, 2018 at 10:47
  • Have you inspected the DOM using the browsers developer tools? Is the class being applied, or not? Commented Jul 23, 2018 at 10:50
  • <div _ngcontent-c1="" class="form-group has-error"> I get this in console @user184994 I think it's not applied Commented Jul 23, 2018 at 10:52
  • Right, so according to that the has-error class has been added, it sounds like the style hasn't. Are you using Bootstrap? Commented Jul 23, 2018 at 10:53
  • yes I am using latest bootstrap in Index.html @user184994 Commented Jul 23, 2018 at 10:54

2 Answers 2

1

Maybe use this instead?

[ngClass]="hasErros? 'some-class' : 'some-other-class'"
Sign up to request clarification or add additional context in comments.

Comments

0

You can modify your input tag and use [ngClass] attribute to change input tag border line to red or any color and same can be done for text too.

<input [ngClass]="{'decorate-red' : !mAddress_Model.mFName && flag, 'decorate-regular' : mAddress_Model.mFName && !flag}" type="text" required minlength="4" id="Name" name="Name" class="form-control "  [(ngModel)]="mAddress_Model.mFName"  #Name="ngModel">

If there is an error then assign flag value to false else true.

in css add

.decorate-red {
   border: 1px solid red !important;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.