Conditionally applying css to mat form field

给你一囗甜甜゛ 提交于 2021-01-29 13:21:24

问题


I am working on an angular application and I am using mat form fields in it. For changing color of botttom border of mat form field I am using mat-form-field-ripple css which is inbuilt for mat form field. CSS is as follows.

.mat-form-field-ripple {
    background-color: #f9c940!important;
}

When I use this CSS, it automatically gets applied to all form fields. I have to apply #f9c940 color in mat-form-filed-ripple in when one condition is true and a different color when another condition is true. My mat form field code is as follows:

                        <mat-form-field appearance="fill">
                            <mat-label [ngClass]="{}">Name</mat-label>
                            <input formControlName="Name" readonly>
                        </mat-form-field>

I was trying to do it using ngClass as shown above but not getting it. How can I do that?


回答1:


You can apply classes conditionally like this:

<mat-label [ngClass]="{'your-class': foo=='foo', 'your-class-another':bar=='bar' }">
    Name
</mat-label>



回答2:


Just create your own CSS class:

.mat-form-field-ripple {
    //your standard styling,
}

.myBackgroundColor {
    background-color: #f9c940!important;
// add this selector below the .mat-form-field-ripple selector so that it will override..
}

Then apply it conditionally to your label:

<mat-form-field appearance="fill">
    <mat-label [ngClass]="{'myBackgroundColor': mycheck}">Name</mat-label>
    <input formControlName="Name" readonly>
</mat-form-field>

In your component you have the expression it is based on:

mycheck = true; // you will modify this true to any expression that is transformable to a boolean. If true, your class is applied, if false then not..


来源:https://stackoverflow.com/questions/61307041/conditionally-applying-css-to-mat-form-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!