【问题标题】:Using Component styles results in conflicting html/body styles使用组件样式会导致 html/body 样式冲突
【发布时间】:2016-01-13 12:19:48
【问题描述】:

我的 Angular 2 应用程序中有两个组件,它们在 SASS 文件中定义了不同的样式。不幸的是,这两个组件的样式似乎都在加载,导致 html 和 body 样式冲突。

我的组件定义如下所示:

@Component({
    selector: 'signup',
    directives: [RouterOutlet, RouterLink],
    styles: [require('../sass/signup.scss').toString()],
    template: require('./signup.component.html')
})

@Component({
  selector: 'signin',
  directives: [RouterOutlet, RouterLink],
  styles: [require('../sass/signin.scss').toString()],
  template: require('./signin.component.html')
})

样式表如下所示:

// signup.scss
html, body {
    height:100%;
    background-color: #eaeaea;
    display: flex;
    align-items: center;
    justify-content: center;
    display: -webkit-flex;
    -webkit-align-items: center;
    -webkit-justify-content: center;
}

// signin.scss
html, body {
    height:100%;
    background-color: #373746;
    display: flex;
    align-items: center;
    justify-content: center;
    display: -webkit-flex;
    -webkit-align-items: center;
    -webkit-justify-content: center;
}

两个组件的背景颜色都是#373746

有什么想法吗?我可以轻松地创建两个单独的 <div>s 并带有 id 或类,但这将是一种解决方法;随着我的应用程序的增长,我真的不想跟踪为哪些组件定义了哪些样式。

【问题讨论】:

    标签: angular sass


    【解决方案1】:

    如果您在 ng2 组件中添加 styles,这是为了设置它们的样式,而不是整个页面(您使用选择器 htmlbody 所做的事情)。

    你可以这样做:

      @Component({
          selector: 'signup',
          directives: [RouterOutlet, RouterLink],
          styles: ['
            signup {
              background-color: red;
            }
          '],
          template: '<p>I\'m the signup with red background!</p>'
      })
    
      @Component({
          selector: 'signin',
          directives: [RouterOutlet, RouterLink],
          styles: ['
            signin {
              background-color: blue;
            }
          '],
          template: '<p>I\'m the signin with blue background!</p>'
      })
    

    【讨论】:

    • 嗯,我的组件在页面上垂直和水平居中,这个建议只为组件的背景着色,而不是整个页面。如何更改页面之间的背景颜色?
    • 我只是写这个例子来向你展示 ng2 组件中的styles 必须只适用于它们。然后您可以添加一个应用于整个页面的 css 文件或添加另一个包含 signupsignin 的组件以及适用于两者的样式。如果您想了解更多详细信息,请发送带有特定案例的 plunker。
    • 谢谢@bertrandg。我会让组件全屏来解决这个问题。
    【解决方案2】:

    你总是可以给你的 body 一个 id,然后在相关的组件 typescript 文件中改变背景 css 属性:

    ngOnInit () {
        document.getElementById('body').style.background-color = "#eaeaea";
    }
    

    【讨论】:

      猜你喜欢
      • 2012-02-09
      • 2011-09-06
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2012-12-07
      • 2019-03-27
      • 1970-01-01
      相关资源
      最近更新 更多