Angular 5+Material 5.2:输入框非空时修改占位符颜色问题求助
The key here is leveraging the built-in state classes that Angular Material adds to the mat-form-field container. When an input has a non-empty value, Material automatically applies the mat-form-field-has-value class to its parent mat-form-field element. We can use this class to target the placeholder specifically for filled inputs.
Step 1: Add the CSS Selector
Use this CSS to change the placeholder color only when the input has a value:
Option 1: Global Styles (styles.css)
This works without needing to break view encapsulation:
/* Target placeholder for inputs with a value */ .mat-form-field-has-value .mat-input-element::placeholder { color: #2196F3; /* Replace with your desired color */ opacity: 1; /* Ensures full color visibility (browsers often default to 0.5 opacity) */ } /* Optional: Keep your existing focus style */ .mat-form-field.mat-focused .mat-input-element::placeholder { color: #1976D2; /* Your preferred focus color */ }
Option 2: Component-Scoped Styles
If you want to apply this only to a specific component, use ::ng-deep to penetrate Angular's view encapsulation (required because Material components use their own encapsulation):
::ng-deep .mat-form-field-has-value .mat-input-element::placeholder { color: #2196F3; opacity: 1; } ::ng-deep .mat-form-field.mat-focused .mat-input-element::placeholder { color: #1976D2; }
Why This Works
mat-form-field-has-value: This class is added by Angular Material only when the input has a non-empty value, so it won't affect empty inputs.::placeholder: Targets the native input placeholder (works across modern browsers).opacity: 1: Overrides the default browser behavior that makes placeholders semi-transparent, ensuring your color shows as intended.
Common Pitfall to Avoid
Don't try using input:not(:empty)::placeholder—the :empty pseudo-class checks for child nodes, not the input's value, so it won't work for form inputs. Always rely on Material's state classes for consistent results.
内容的提问来源于stack exchange,提问作者stackUser44

