【问题标题】:Apply styles to specific for angular material components from global css files将样式应用于全局 css 文件中的特定角度材质组件
【发布时间】:2020-12-25 17:49:56
【问题描述】:

我正在尝试通过外部 css 文件在我的应用程序中设置特定 mat 输入元素的样式。

例如我已经导入了 textfield.css 文件 style.css 文件进行样式设置。

所以让我在下面写一些代码

 <mat-form-field>
                <input class="txtfieldwithBordergreen" formControlName="password" matInput type="Password" placeholder="password">
             
              </mat-form-field>

所以下面是我的应用类"txtfieldwithBordergreen"的html文件

我想通过在需要的地方应用这个类来控制任何文本字段的属性。

制作textfield.css文件并导入style.css文件

下面是textfield.css文件的代码

.mat-form-field-appearance-legacy .mat-form-field-label {
    background-color: green !important;
}

textfield.css 包含在 styles.css 中

所以下面是 style.css 文件

@import 'globalcss/textfield.css';

html, body { height: 100%; padding: 0; margin: 0; }
body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }


:root {
  --primary-color: #fff;
  --background-color: #e5e5e5;
  --text-color: #2d2d2d;
}

这种样式将应用于所有 matInputs 但我想要特定的输入,所以我这样写

.txtfieldwithBordergreen .mat-form-field-appearance-legacy .mat-form-field-label {
        background-color: green !important;
    }

我怎么不知道上面的代码不起作用...当我删除 .txtfieldwithBordergreen 它通过应用到所有 mat 输入时工作正常。

任何线索我哪里出错或需要任何更新?

附言 我的目标是构建 pre css 类,如

文本字段较小 textfield-big 等。只需将类名应用于 mat 输入,这样我就不需要去更改相应的 css 文件了。

任何帮助将不胜感激..!!

【问题讨论】:

  • 最好的方法是打开您的开发工具并找到您想要与众不同的确切元素。然后,您可以从开发工具中找出产生当前样式的规则。一旦你知道了这一点,你就可以弄清楚如何将你的类注入到混合中。如果原始样式是由 .mat-form .mat-form-field .mat-form-field-label 生成的,那么您可以使用 .my-green 将您的类添加到您的字段,并将您的 css 添加到 .mat-form- field.my-green .mat-form-field-label。请记住,空格表示父->子,而没有空格表示同一元素上的两个类
  • 我会检查并让您知道,感谢您的明确指导。

标签: css angular angular-material


【解决方案1】:

创建一个名为 textfield.css

的单独文件

将其导入您的 style.css 之类的

@import 'globalcss/textfield.scss';

将该文件放在 globalcss 文件夹中,使该文件夹在 src 下

src=>globalcss=>textfield.scss

现在您可以使用任何 matInput 并添加类似 small-text-field 的样式,请参阅下面添加的类

    <mat-form-field class="small-text-field"> 
               <input matInput placeholder="Username">
            </mat-form-field>

textfield.css 文件中的内容是这样的

.mat-form-field.smallTextfield .mat-form-field-wrapper{
    font-size: 10px;
    width: 125px;
}

所以在整个应用程序中,无论你有 matInput,如果你应用这个类,它就会被添加,但请注意,现在 ng::deep 已被弃用,使用 ts 文件中的以下指令作为

封装:ViewEncapsulation.None

这将在内部使用

@Component({selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
encapsulation: ViewEncapsulation.None})

【讨论】:

    猜你喜欢
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    相关资源
    最近更新 更多