【问题标题】:How to change font color of matautocomplete options如何更改 matautocomplete 选项的字体颜色
【发布时间】:2021-09-20 04:28:05
【问题描述】:

我想更改自动完成面板中显示的 mat-option 的字体颜色。

我在根 style.css 中定义了样式

::ng-deep .mat-option-text {
  color: red !important;
}

但是,当我在浏览器检查元素面板中设置颜色属性时,我看到了变化

template.html 我应该在模板类或 style.css 中做哪些更改来更改 mat-options 的字体颜色。

<label>Search names</label>
<input type="text"
       placeholder="search name"
       aria-label="Number"
       matInput
       [formControl]="myControl"
       [matAutocomplete]="auto">
     
<mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
      {{option}}
    </mat-option>
</mat-autocomplete>

template.ts

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';

@Component({
  selector: 'app-matautocom',
  templateUrl: './matautocom.component.html',
  styleUrls: ['./matautocom.component.css']
})
export class MatautocomComponent implements OnInit {

  names: string[] = ['ghui', 'ustu', 'caty','momo', 'rekh', 'john', 'kemp'];
  myControl: FormControl = new FormControl();
  filteredOptions: Observable<string[]> | undefined;
  constructor() { }

  ngOnInit(): void {
    this.filteredOptions = this.myControl.valueChanges.pipe(
      startWith(''),
      map(value => this._filter(value))
    );
  }
  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();
 
     return this.names.filter((option) =>  {
       console.log(filterValue)
      option.toLowerCase().includes(filterValue);
      return option;
    })   
   
  }

}


【问题讨论】:

  • 您能否为您的代码创建 stackblitz 演示?

标签: javascript css angular typescript


【解决方案1】:

试试这个

::ng-deep input.mat-input-element { 颜色:红色; }

或者这个

::ng-deep .mat-option.mat-active { 红色; }

【讨论】:

    【解决方案2】:

    全局 style.css 只是一个普通的、非 Angular 或至少非封装的样式表。您应该删除::ng-deep,这样它才能工作。


    解决方案 1:删除全局 style.css 中的 ::ng-deep

    style.css(全局)

    .mat-option-text {
      color: red !important;
    }
    

    Sample solution 1 on StackBlitz


    解决方案 2:将样式规则放在 MatautocomComponent 的 CSS 文件中。

    matautocom.component.css

    ::ng-deep .mat-option-text {
      color: red !important;
    }
    

    Sample solution 2 on StackBlitz

    【讨论】:

      猜你喜欢
      • 2012-06-22
      • 2011-03-19
      • 2023-02-08
      • 2023-03-07
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 2018-03-03
      • 2015-05-18
      相关资源
      最近更新 更多