模板驱动表单中,输入框含.ng-invalid时如何修改对应标签颜色?
Absolutely! You can absolutely sync your label's color with the input's invalid state—here are two straightforward, reliable ways to pull this off in Angular's template-driven forms:
Method 1: Use Angular Template Variables & Dynamic Class Binding (Recommended, Most Compatible)
This approach leverages Angular's built-in form state tracking to dynamically apply a red color class to your label when the input is invalid and touched. It works across all modern browsers and integrates cleanly with template-driven form logic.
First, update your template to add ngModel (required for state tracking) and a template variable to access the input's state. Then bind a color class to the label based on that state:
<div class="form-group"> <!-- Bind red color class when input is invalid and touched --> <label for="guitar" class="col-sm-6" [class.text-danger]="guitarInput.invalid && guitarInput.touched">Guitar:</label> <div class="col-sm-6"> <!-- Add ngModel, template variable, and validation rules --> <input id="guitar" type="text" class="form-control" #guitarInput="ngModel" required pattern="[a-zA-Z0-9 ]*" > <p *ngIf="guitarInput.invalid && guitarInput.touched">Warning!</p> </div> </div>
Add this CSS to define the red color class (or use Bootstrap's built-in text-danger if you're using Bootstrap):
.text-danger { color: #dc3545; /* Custom red or Bootstrap's danger color */ } /* Your existing input invalid style */ input.form-control.ng-invalid.ng-touched { border: 2px solid red; }
How it works:
- The
#guitarInput="ngModel"template variable gives you access to the input's form state properties (likeinvalidandtouched). - The
[class.text-danger]binding adds the red color class only when the input is both invalid (failed validation rules likepatternorrequired) and touched (the user has interacted with it).
Method 2: CSS :has Pseudo-Class (Modern Browsers Only)
If you prefer not to modify your template logic, you can use the CSS :has pseudo-class to target the label directly based on the input's state. Note that this only works in modern browsers (Chrome, Firefox 121+, Edge, Safari 15.4+).
Add this CSS to your stylesheet:
/* Your existing input invalid style */ input.form-control.ng-invalid.ng-touched { border: 2px solid red; } /* Target the label when the nested input is invalid and touched */ .form-group:has(> div > input.form-control.ng-invalid.ng-touched) > label { color: red; }
Key Note:
Don't forget to add validation rules to your input (like required or pattern in Method 1). Without these, Angular won't apply the ng-invalid class to the input, so none of these styles will trigger.
内容的提问来源于stack exchange,提问作者Naturo Power

