Search code examples
cssangularsassangular-material

Apply .mat-column-name styles to child component in Angular Material


Child component contains an Angular material table, that is created based on columns passed as input:

<table mat-table>
  <ng-container *ngFor="let col of columns" [matColumnDef]="col">
</table>

@Input() columns: string[]

Parent component provides columns definitions. However, the only way I can affect f.e. mat table column width is by setting the stylesheet with

.mat-column-col-name {
  width: 10px
}

How can I set mat-column width from the parent component? Names of columns are known by parent, can be defined in it's stylesheet. I strongly want to avoid any encapsulation: none, because child component is inside a library I develop. Passing styles as @Input() would be the best solution.

Edit: I'm also using material themes, which prevents styles outside library from applying, I'd love not to change lib interfaces if possible:

// Library
$theme: map.merge(
  primary: mat.define-palette($my-palette-grey),
  secondary: mat.define-palette($my-palette-blue)
);

// Child in lib
@mixin theme($theme) {
 .my-table-component {

// Parent global css
@use '@my-lib/src/theme' as theme;
@use '@my-lib/table/src/theme/table-component' as table;
@include table.theme($theme);

Therefore:

.wrapper {
  .my-table-component {
    border: 5px solid red; // easily applied, even without !important
    .mat-column-type {
      width: 99em !important; // Never applied

Solution

  • We can use ::ng-deep to make the styles visible from the parent to the children like so

    :: ng-deep .mat-column-col-name {
      width: 10px
    }
    

    If you are not a fan of ::ng-deep, I would suggest add a class to the parent element that wraps the child .wrapper-class, then going to the angular global styles file either styles.scss or global-styles.scss and applying the styles, this will scope the styles to only this class element and its children, the file will be located on the src folder!

    .wrapper-class .mat-column-col-name {
      width: 10px
    }
    

    parent:

    <div class="wrapper-class">
        <child-component/>
    </div>