VinoPravin
VinoPravin

Reputation: 987

Angular Load css partially

I want to know is there any wany to load or restrict particular css in index HTML.

I'm using angular 4 where I separated my components as admin and user components. Both the components using their own CSS. But the Problem is When I include 'admin.css' and 'user.css' in the index.html both getting merged and giving me some ugly UI. I want to show include 'user.css' only if the user points to the user's URL and same for the admin scenario if the user points to admin URL, it should load 'admin.css' give me a suggestion or solution to achieve this.

Thanks in advance

Upvotes: 0

Views: 1380

Answers (2)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24424

It 's better and easy if you use sass and create a class flag for user and admin components like this

theme/_user.scss

.user { 
  label { 
    color:red;
  }
}

theme/_admin.scss

.admin { 
  label {
    color:green;
  }
}

and this in main style.scc

@import "theme/_user.scss";
@import "theme/_admin.scss";

note : _user.scss will have all the style from user.css this is much better for app performance you will have one style file with user and admin style

stackblitz example

Upvotes: 0

severus256
severus256

Reputation: 1723

First of all - using Angular 4 - the best practice to include .css files for each component.

I mean:

You have a component user.ts, so you should to include style for the user to that component, not to index.html

Example:

user.ts code:

@Component
....
styles: ['h1 { font-weight: normal; }']

Or

@Component
....
styleUrls: ['./user.css']

That's will isolate your styles. As it said at Angular docs:

By default in Angular, when you attach CSS directly to a component, we scope that css exclusively to that component. This scoping isolates it from the rest of your application. This additional capability means that there are two ways to use CSS with Angular.

Upvotes: 1

Related Questions