2

I am implementing validation in my angular 4 validation and need to do some tweaks. The validation works fine but probably need to alter the way the message is displayed. At the moment when i click the save button on the form the control a message is displayed below the control and control borders get highlighted in red as well the control label. I dont want to the control label to be highlighted in red. One way i can think of is using the regular label tag but cant i achieve the same using label for. Is (label for) recommended ? what are the benefits. ? How do I use (label for) and yet not highlight the label

<form [formGroup]="newMovieForm" (ngSubmit)="save(newMovieForm.value, newMovieForm.valid)">
  <div class="col-sm-12">
    <div class="form-group col-sm-6">
      <div class="form-group" [ngClass]="{'has-error':!newMovieForm.controls['title'].valid && (saveClicked || newMovieForm.controls['title'].touched)}">
        <label for="movie-title" class="control-label">Title of Movie</label>
        <input type="text" class="form-control" id="movie-title" placeholder="Title of Movie" formControlName="title" maxlength="100">
        <!-- The hasError method will tell us if a particular error exists -->
        <div *ngIf="newMovieForm.controls['title'].hasError('required') && (saveClicked || newMovieForm.controls['title'].touched)" class="alert alert-danger">Title is required.</div>
      </div>
    </div>
</form>
Kim Kern
  • 54,283
  • 17
  • 197
  • 195
Tom
  • 8,175
  • 41
  • 136
  • 267

1 Answers1

2

This has nothing to do with using the for attribute. The reason your label is highlighted in red is because it has the control-label class applied:

.has-error .control-label {
    color: #a94442;
}

You can just remove that class from your label to get the result you want. Looking at the source code, this class only affects label colours, unless used in horizontal, inline or navbar forms.

If you still want to use control-label, you could always override the CSS to reset the colour, but this will be unnecessary in your exact example.

This answer explains the use of the for attribute specifically, but as I've said, that's not impacting the highlighting of your label here.

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203