ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Angular Component Styles

In this tutorial, we look at various ways by which we can style our Angular Components. We looked at how to apply global styles to the Angular app. You can apply styles to Components in various ways. For example, using inline style, external style, template inline style, ngClass directive, ngStyle directive, etc. We cover all of these in this article on Angular Component styles

The Angular Components maintain their own style & state. But CSS styles are global in scope. The angular encapsulates the component styles using the View Encapsulation strategies. Therefore ensuring that the styles of one component do not bleed into another view.

Further Reading On Component styles

  1. View Encapsulation in Angular
  2. Angular global CSS Style
  3. Shadow DOM
  4. Using Shadow DOM

Example Application

Create a new angular application

                              
ng new ComponentStyle
                            
                        

Create three component as shown below

                              

ng g c home
ng g c test1
ng g c test2
                            
                        

Copy the following code to AppRoutingModule

                              

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { Test1Component } from './test1/test1.component';
import { Test2Component } from './test2/test2.component';
import { HomeComponent } from './home/home.component';
 
const routes: Routes = [
    {path:'',redirectTo:'home',pathMatch:'full'},
    {path:'home',component:HomeComponent},
    {path:'test1',component:Test1Component},
    {path:'test2',component:Test2Component},
];
 
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
 
 
                            
                        

Copy the following code to app.component.html

                              
 
<!--The content below is only a placeholder and can be replaced.-->
  <h1>
    Welcome to {{ title }}!
  </h1>
 
  <p>This para is from app component</p>
 
<ul>
  <li><a [routerLink]="['/home']" routerLinkActive="router-link-active">Home</a> </li>
  <li><a [routerLink]="['/test1']" routerLinkActive="router-link-active">Test1</a> </li>
  <li> <a [routerLink]="['/test2']" routerLinkActive="router-link-active" >Test2</a></li>
</ul>
 
<router-outlet></router-outlet>
 
 
                            
                        

How to add styles to Angular Components

The Angular allow us the specify the component specific styles. There are four ways you can apply style.

  1. Component Inline style
  2. Component External Style
  3. Template using link directive
  4. Template using style directive

Component Inline Style

Use the styles: metadata of the @Component or @Directive to specify the CSS rules as shown below.

                              

@Component({
  selector: 'app-test1',
  templateUrl: './test1.component.html',
  styles: [
    `p { color:blue}`
  ],
})
 
 
                            
                        

Use backtick character to enter the multi-line style.

You can add multiple styles by separating each other using a comma as shown below.

                              

styles: [
    `p { color:blue}`,
    `h1 {color:blue}`  
  ],
 
                            
                        

Component External Style

Specify the external style sheets using the styleUrls: meta data of the @Component decorator or @directive directive.

                              
 
@Component({
  selector: 'app-test2',
  templateUrl: './test2.component.html',
  styleUrls: ['./test2.component.css'],
})
                            
                        

You can add multiple styles by separating each other using a comma as shown below

                              

styleUrls: ['./test2.component.css','.another.stylesheet.css'],
 
                            
                        

You can specify both Component inline & Component External style together as shown below

                              

@Component({
  selector: 'app-test2',
  templateUrl: './test2.component.html',
  styles:[`p {color:yellow}`],
  styleUrls: ['./test2.component.css'],
})
                            
                        

Template Inline Style using style tag

We can also specify style within the component template file by using the style or link> tags as shown below

test2.component.html
                              

<style>
  p {
    color: purple;
  }
  </style>
 
<p>
  test2 works!
</p>
 
                            
                        

Template Inline Style using link tag

You can add the external style sheets using the the link tag as shown below. The path must be relative to the index.html

                              

<link rel="stylesheet" href="assets/css/morestyles.css">
<p>
  test2 works!
</p>
 
                            
                        

You can also load the CSS from an external source as shown below

                              

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
 
<p>
  test2 works!
</p>
 
 
                            
                        

Style Priority

The styles are applied in the following order

  1. Component inline styles i e. Styles defined at @Component.styles
  2. Component External styles i.e. @Component.styleUrls
  3. Template Inline Styles using the style tag
  4. Template External Styles using the link tag

Other ways to add style to component

The above method lists the various ways you can style the entire component. There are a few ways you can add style to individual elements in the angular

  1. Angular Classes with ngClass Directive
  2. Angular Styles with ngStyle directive
  3. Angular className directive
  4. Angular Class Binding
  5. Angular Style Binding