Search code examples
csscomponentsmarkdownborder

::ng-deep changes other components style


I am using a .md file to display information in a dialog from Material for Angular. The thing is that tables in markdown files, when they are displayed in the DOM, there are no borders. So I tried to add some css.

::ng-deep table {
  border-collapse: collapse;
  border-spacing: 0;
  border:2px solid black;
}

::ng-deep th {
  border:2px solid black;
}

::ng-deep td {
  border:1px solid black;
}

If don't add ::ng-deep, no style is applied on my table, so I am forced to use it. It works fine, my table now has borders but it affects my other components, how to fix that ?

EDIT : this is my template :

<div markdown [src]="data"></div>


Solution

  • Answer is add parent class to dialog and use ::ng-deep to apply styles for that component only

    You can add class to dialog as shown below

    const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
          width: '250px',
          data: {name: this.name, animal: this.animal},
          panelClass: 'my-parent-class'
    });
    

    and add styles as

    .my-parent-class ::ng-deep table {
      border-collapse: collapse;
      border-spacing: 0;
      border:2px solid black;
    }
    
    .my-parent-class ::ng-deep th {
      border:2px solid black;
    }
    
    .my-parent-class ::ng-deep td {
      border:1px solid black;
    }
    

    Explanation: Material dialog is a dynamic component

    Static component HTML

    <table _ngcontent-c0>...</table>
    

    Static component CSS

    table[_ngcontent-c0] { ... }
    

    Dynamic component HTML

    <table>...</table>
    

    Dynamic component CSS

    table { ... }
    

    Notice the difference for static component attribute _ngcontent-c0 is added by angular, Angular use this Technic to create component specific styles (To apply styles for that particular component), but for dynamic component no attribute is being added. This is the reason your static component styles not applied to dynamic component

    To make this work we used ::ng-deep before any class to remove that attribute _ngcontent-c0 and select dynamic component, so when ::ng-deep is used your styles are no more component specific (it will be applied to all components). This is the reason we use parent class to apply styles for that component only and dynamically created component too.