You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 5+Material 5.2:输入框非空时修改占位符颜色问题求助

Solution for Angular 5 + Material 5.2: Change Placeholder Color When Input Has Value

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:50:14