【问题标题】:Set custom classes with angular 8使用角度 8 设置自定义类
【发布时间】:2019-09-17 19:10:05
【问题描述】:

我需要使用银行返回的背景颜色创建类,我如何使用 Angular 来做到这一点?我知道有办法做到这一点,也许使用@ViewChildren。

这些是我将在返回数据库时创建的类,我将在其中设置人员姓名和背景颜色,我需要在渲染组件时设置此 css。

.schedule-group-custom-work-days.e-schedule .e-month-view .e-work-days.eduard,
.schedule-group-custom-work-days.e-schedule .e-vertical-view .e-work-hours.eduard {
    background-color: rgba(0, 139, 139, 0.26);
}

.schedule-group-custom-work-days.e-schedule .e-month-view .e-work-days.alice,
.schedule-group-custom-work-days.e-schedule .e-vertical-view .e-work-hours.alice {
    background-color: #deecfc;
}

.schedule-group-custom-work-days.e-schedule .e-month-view .e-work-days.roger,
.schedule-group-custom-work-days.e-schedule .e-vertical-view .e-work-hours.roger {
    background-color: rgba(210, 105, 30, 0.39);
}

【问题讨论】:

    标签: angular typescript sass


    【解决方案1】:

    您可以使用Renderer2 创建一个style 标签元素,并且您可以从component 插入您的自定义css,最后您可以将该标签注入到您的文档正文中:

    constructor(private renderer2: Renderer2) {
    let myCss = `.schedule-group-custom-work-days.e-schedule .e-month-view .e-work-days.eduard,
                          .schedule-group-custom-work-days.e-schedule .e-vertical-view .e-work-hours.eduard {
                                background-color: rgba(0, 139, 139, 0.26);
                          }
    
                      .schedule-group-custom-work-days.e-schedule .e-month-view .e-work-days.alice,
                       .schedule-group-custom-work-days.e-schedule .e-vertical-view .e-work-hours.alice {
                              background-color: #deecfc;
                        }
    
                        .schedule-group-custom-work-days.e-schedule .e-month-view .e-work-days.roger,
                        .schedule-group-custom-work-days.e-schedule .e-vertical-view .e-work-hours.roger {
                            background-color: rgba(210, 105, 30, 0.39);
                        }`;
    
    let styles = document.createElement('style');
    
    styles.type = 'text/css';
    styles.appendChild(document.createTextNode(myCss));
    this.renderer2.appendChild(document.body, styles);
    
    }
    

    【讨论】:

    • 对,这是动态应用 css 的最佳实践吗?我必须使用 Renderer2 来删除类吗?或者当我不想在屏幕上显示元素时是否不需要删除?
    • 好吧,我不确定它是否是实现这一目标的最有效方法,但它可以完成这项工作,如果你想删除可以使用 Renderer2 更新的类,它也不会影响你的样式仍然喜欢它,但摆脱未使用的 css 总是更好。
    猜你喜欢
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 2014-08-13
    相关资源
    最近更新 更多