简体   繁体   中英

How to load angular material css

I have basic navigation and two components.

Component1 uses MatTable, but Component2 pure HTML table with material css classes:

<table class="mat-table mat-elevation-z8">
  <tbody>
    <tr class="mat-row">
      <td class="mat-cell">

When I navigate to Component1 and then to Component2 everything is nice. However when I navigate to Component2 first, the some of material styling is missing, eg the table lines.

How to correctly use material css in angular without using material components

The best way to import material theme to your app, in my opinion is adding to your (src/styles.scss, considering you are using SCSS preprocessor):

// material theming
@import '../node_modules/@angular/material/theming';
@include mat-core();
@import 'my-theme';

// create the default theme
@include angular-material-theme($my-theme);

then, include your own theme (my-theme.scss):

$my-primary: mat-palette($mat-blue_gray, 800);
$my-accent: mat-palette($mat-green, 400);
$my-warn: mat-palette($mat-red);

$my-theme: mat-light-theme($my-primary, $my-accent, $my-warn);

How to correctly use material css in angular without using material components

The short answer is that you cannot do this. For a more thorough explanation, see Using Angular Material classes outside Angular pages .

To reiterate the points of that post, the main thing you need to understand is that <table mat-table> is an Angular Component, whereas <table class="mat-table"> is just a <table> with a class. When you use the component, you get all of the encapsulated style that belongs to the component only, not just style defined in the global style sheet for the class "mat-table". Of course, as stated in the link, style is style, css is just css, so using the material classes will do something, but it won't do everything you probably want.

The only disgusting workaround I found is including an empty mat-table before or after your custom table.

<table mat-table>
    <ng-container matColumnDef="workaround">
        <td mat-cell *matCellDef="let element">workaround</td>
    </ng-container>
    <tr mat-row *matRowDef="let row; columns: ['workaround'];"></tr>
</table>

<table class="mat-table mat-elevation-z8">
  <tbody>
    <tr class="mat-row">
      <td class="mat-cell">
...

This way, it will include all the required CSS.

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