简体   繁体   中英

How to override styles of reusable component in Angular2?

I have reusable component "two-column-layout-wrapper" which styles are in main file .css. I want to use this component in another module, but I need different width of 2 classes. How can I override styles?

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 {

}

You have a couple of options.

The first is to give your component a class/style from its parent, and then if you need to have inner elements that need to change you can use the /deep/ selector in the parent element CSS. For example: .parent-appended-class /deep/ .child-element-class { ... }

Alternatively if you want to keep the CSS in the child component, you can pass an attribute from the parent to the child so that the child can react accordingly (by setting its own class according to the attribute passed) using the @Input decorator. Detailed explanation here .

That way ?

@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 {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM