错误时更改材料输入的颜色

时间:2017-02-08 15:10:39

标签: angular angular-material2

enter image description here

我想在脏和无效时更改md输入颜色红色(与图像中的国家/地区下拉相同)。我已经阅读了很多文章,但没有找到任何帮助..

3 个答案:

答案 0 :(得分:1)

您需要包含以下css

 .mat-input-invalid .mat-input-placeholder {
    color: red;
}

.mat-input-invalid .mat-input-ripple {
    background-color: red;
}

答案 1 :(得分:1)

它可以通过css解决,但需要有关封装的准备工作,以避免使用::ng-deep等弃用的变体。这里给出了一个解决方案:

https://stackoverflow.com/a/46042645/2692283

以下是您案例的简短说明:

  1. 在您的组件中设置encapsulation: ViewEncapsulation.None

    import { ViewEncapsulation } from '@angular/core';
    
    @Component({
        ...
        encapsulation: ViewEncapsulation.None
    })
    

    这里给出了更详细的解释:

    ::ng-deep going to be deprecated - Any alternatives?

  2. 现在只需使用css将其设为红色:

    /* Sets the underline to red if dirty and invalid */
    .mat-form-field.ng-dirty.ng-invalid .mat-form-field-underline {
      background-color: red;
    }
    /* Sets the label to red if dirty and invalid */
    .mat-form-field.ng-dirty.ng-invalid .mat-form-field-label {
      color: red;
    }
    
  3. 它适用于Angular 4和5。

答案 2 :(得分:0)

将错误颜色设置为主题中的警告颜色。

https://material.angular.io/guide/theming

@import '~@angular/material/theming';
// Plus imports for other components in your app.

// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// Be sure that you only ever include this mixin once!
@include mat-core();

// Define the palettes for your theme using the Material Design palettes available in palette.scss
// (imported above). For each palette, you can optionally specify a default, lighter, and darker
// hue. Available color palettes: https://material.io/design/color/
$candy-app-primary: mat-palette($mat-indigo);
$candy-app-accent:  mat-palette($mat-pink, A200, A100, A400);

// The warn palette is optional (defaults to red).
$candy-app-warn:    mat-palette($mat-red);

// Create the theme object (a Sass map containing all of the palettes).
$candy-app-theme: mat-light-theme($candy-app-primary, $candy-app-accent, $candy-app-warn);

// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
@include angular-material-theme($candy-app-theme);