【问题标题】:How to override styles of reusable component in Angular2?如何覆盖Angular2中可重用组件的样式?
【发布时间】:2017-11-29 07:14:28
【问题描述】:

我有可重用组件“双列布局包装器”,其样式位于主文件 .css 中。我想在另一个模块中使用这个组件,但我需要不同宽度的 2 个类。如何覆盖样式?

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Response } from '@angular/http';


@Component({
selector: 'italik-managepackages',
styles: [` 
    :host { 
        display: flex;
    }
`],
template: `
    <div two-column-layout-wrapper>
        <div sidebar-component italik-managepackages-overview></div>
    </div>
`
})
export class ManagePackagesComponent {

}

【问题讨论】:

  • 创建一个新的自定义 CSS,复制规则,设置新的属性值并在 主要的之后加载它

标签: javascript css angular


【解决方案1】:

你有几个选择。

首先是给你的组件一个来自其父级的类/样式,然后如果你需要有需要更改的内部元素,你可以在父元素 CSS 中使用/deep/ 选择器。 例如:.parent-appended-class /deep/ .child-element-class { ... }

或者,如果您想将 CSS 保留在子组件中,您可以使用 @987654324 将属性从父组件传递给子组件,以便子组件可以做出相应的反应(通过根据传递的属性设置自己的类) @装饰师。详解here.

【讨论】:

  • 好的。但是我必须把这些样式放在哪里?样式:[` :host { display: flex; } .max-width-300px /deep/ .max-width-500px { 宽度:800px !important; } `],像这样吗?
  • 是的,你应该把它放在父组件的样式中,它会影响子组件。
【解决方案2】:

这样吗?

@Component({
  template: `
    <h1>Parent/h1>
    <child [style.color]="'blue'"></test-cmp>
  `
})
export class ParentComponent {
}

@Component({
  selector: 'child',
  template: `
    <h1>Child text should be blue</h1> 
  `,
  styles: [`
    :host{color: red; } 
    `
})
export class ChildComponent {
}

【讨论】:

    猜你喜欢
    • 2016-09-30
    • 2021-11-01
    • 1970-01-01
    • 2017-12-29
    • 2017-03-01
    • 2020-07-26
    • 2017-04-27
    • 2020-04-04
    • 2019-11-30
    相关资源
    最近更新 更多