【问题标题】:Applying common styles in angular在 Angular 中应用常见样式
【发布时间】:2020-08-07 14:13:00
【问题描述】:

我的 Angular 应用程序中有两个组件共有的样式。目前,我将它们应用于各个组件的 scss 文件中。我有一个名为 styles.scss 的根 scss 文件

使样式通用的最佳做法是什么

常见的样式有

h2 {
  margin-left: 15px;
}

form {
  margin: 15px;

  label {
    display: block;
  }

  input, select, button {
    display: block;
    width: 250px;
    margin-bottom: 15px;
  }

  small {
    color: red;
    margin-top: -12px;
    margin-bottom: 15px;
    display: block;
  }
}

table {
  margin: 15px;
  border-collapse: collapse;

  th, td {
    border: 1px solid #ddd;
    padding: 5px;
    min-width: 100px;
    text-align: left;
  }

  th {
    background-color: #ddd;
  }
}

【问题讨论】:

    标签: angular sass


    【解决方案1】:

    Styles.scss 是一个通用样式文件,用于 css 的可重用性,只需将所有通用样式添加到 styles.css 任何类名下,比如说componentStyle

    Styles.css

    componentStyle{
    // all common styles in here
    }
    

    然后在组件中添加 componentStyle 到两个组件的父 div

    ComponentA.html

    <div class="componentStyle">
    this is component A
    <div>
    

    ComponentB.html

    <div class="componentStyle">
    this is component B
    <div>
    

    【讨论】:

    • 如果这能解决您的问题,请点赞并接受
    • 我需要将表单包含在 div 中还是我的组件样式需要导入或继承 style.scss 。每个组件也会有一些特定的样式
    【解决方案2】:

    基本上有两种方法可以实现这一点-

    1. 您可以将您的通用 CSS 代码添加到您在 stlyes.css 中提到的全局 CSS 文件中,该文件存在于根级别,通常所有要编写的通用/共享样式都在多个组件中使用。

    2. 在组件元数据中创建模块明智的style.css 文件和styleUrls 属性接受文件数组,因此您也可以在那里提及。

    应在组件样式文件中添加特定于组件级别的样式

    【讨论】:

      【解决方案3】:

      如果您不想在已经开发的组件上创建包装器,您可以通过使用组件的选择器作为 style.scss 中的包装器来采取一种简单的方法

      app-component-one, app-component-two {
        h2 {
          color: blue;
        }
      }
      

      这将确保组件的样式不会溢出。此外,组件可以在自己的 css 文件中拥有自己的样式。

      【讨论】:

        猜你喜欢
        • 2011-01-09
        • 2020-02-13
        • 1970-01-01
        • 2016-03-05
        • 1970-01-01
        • 2018-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多