无法更改Angular Material输入框占位符的文本颜色。

5

我想要修改 Angular Material 输入框的占位符文字颜色。默认情况下是黑色,但是由于背景颜色为深色,所以我希望它是白色。

我已经阅读了这个站点上所有相关的帖子,但是似乎没有任何方法可以做到这一点。 ::ng-deep 和 mat-placeholder 都不可行。

这是我的 HTML 片段:

    <form #searchForm="ngForm" class="example-full-width mr-auto">
      <mat-form-field style="width: 350px; font-size: 14px; margin-bottom: -15px;">
        <mat-label style="color: white;">Search for an Employee</mat-label>
        <input matInput [(ngModel)]="userIdInput" placeholder="Enter at least 2 characters of a name or ID"

你在调试器中检查过了吗?是否有另一个带有!important的设置正在覆盖它?实际标签是某个具有自己样式的子元素吗? - krillgar
可能是Angular Material Chips placeholder的重复问题。 - wentjun
您可以参考上方的链接。占位符颜色取决于同一类别下的 mat-form-field-label - wentjun
mat-form-field-label类不起作用。我已经设置了ViewEncapsulation.None。 - ts1993
2个回答

6
要改变你的placeholder的css,你只需要修改你的matInput placeholder的颜色即可。你可以在matInput元素中使用mat-input-element类来实现这一点。
理想情况下,我建议您避免使用内联样式,而是使用类。这样做可以使您的代码更易读。

HTML

<form #searchForm="ngForm" class="example-full-width mr-auto">
  <mat-form-field class="employee-search-field">
    <mat-label>Search for an Employee</mat-label>
    <input matInput [(ngModel)]="userIdInput" name="userIdInput" placeholder="Enter at least 2 characters of a name or ID"/>
  </mat-form-field>
</form>

在你的CSS中,添加以下代码。
.employee-search-field {
  width: 350px;
  font-size: 14px;
  margin-bottom: -15px;
}

.employee-search-field mat-label {
  color: white;
  /* add label text color here */
}

.employee-search-field .mat-input-element {
  color: white;
  /* add input text color here */
}

.employee-search-field .mat-input-element::placeholder {
  color: white;
  /* add placeholder css here */
}

2

试试这个

  <mat-form-field>
    <mat-label>Search for an employee</mat-label>
    <input matInput placeholder="Enter at least 2 characters of a name or ID">
  </mat-form-field>

.mat-form-field {
  width: 350px;
  font-size: 14px;
}

::ng-deep .mat-input-element::placeholder {
  color: orange;
}

::ng-deep .mat-form-field-appearance-legacy .mat-form-field-label {
  color: red;
}

我已经尝试过这种方法,但它不起作用。此外,::ng-deep 应该被弃用了。 - ts1993

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接