Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change angular mat-select placeholder color via code

I'm using Angular 5, and would like to change the placeholder text color. The text content of the list is perfectly working (I can change the color), but not the placeholder. I'm not searching an hardcoded solution via the main css of the app, I need to change it dynamically via code.

<mat-form-field>
    <mat-select placeholder="{{'TXTKEY' | translate }}" [style.color]="config.textColor">
        <mat-option *ngFor="let item of items" [value]="item.identifier" (click)="OnChange(item)">
            <div [style.color]="config.textColor"> {{item.name}}</div>
        </mat-option>
    </mat-select>
</mat-form-field>
like image 460
Iteration Avatar asked Mar 24 '18 17:03

Iteration


People also ask

How do I change the select placeholder color?

In most browsers, the placeholder text is grey. To change this, style the placeholder with the non-standard ::placeholder selector.

What is placeholder color code?

The default input placeholder color varies by browser. In your screenshot, it's #8e8e8e. Some examples by browser: In Chrome (Mac) it's #a9a9a9. in Firefox (Mac) it's #777777.

How do you assign a placeholder style?

Use the ::placeholder pseudo-element to style your placeholder text in an <input> or <textarea> form element. Most modern browsers support this, but for older browsers, vendor prefixes will be required.

What is placeholder color CSS?

CSS ::placeholder Selector The placeholder text is set with the placeholder attribute, which specifies a hint that describes the expected value of an input field. Tip: The default color of the placeholder text is light grey in most browsers.


2 Answers

Addressing this subject would be hard with code only. Here is a solution in semi-programatical way. The clue being to use ngClass. You would need to predefine classes, though.

HTML

<mat-form-field>
    <mat-select [ngClass]="className" placeholder="{{someText}}">
        <mat-option *ngFor="let item of items" [value]="item.value">
            {{ item.viewValue }}
        </mat-option>
    </mat-select>
</mat-form-field>

Typescript:

  someText = "Enter your choice";
  someCondition = true;

  get className() {
    return this.someCondition ? 'class1' : 'class2';
  }

CSS:

.class1  .mat-select-placeholder {
  color:red !important;
}

.class2  .mat-select-placeholder {
  color:blue !important;
}

DEMO

like image 162
Vega Avatar answered Nov 16 '22 01:11

Vega


You can use

:host::ng-deep .mat-select-placeholder {
   color: red;
} 

Keep in mind this method will soon be depreciated, so you can add the .mat-select-placholder to your global stylesheet and it should work there also.

like image 31
Mostafa Bagheri Avatar answered Nov 16 '22 02:11

Mostafa Bagheri