Welcome to the free & complete Angular Tutorial.

In this lesson, we are going to discuss about Components in detail.

As you know Component is one of the building block of Angular, we are here to dissect the Component structure and learn how to create it.

To know more about Angular Architecture, below posts will help you.

Angular Architecture Overview

Angular Architecture Explained

Let’s get started.

What is Component?

A component takes control of a portion of screen called View. Let’s consider YouTube web app as an example for the sake of conversation.

Views in YouTube web app (Home page):

  1. Sidebar
  2. Topbar
  3. Content Area (Video thumbnails displayed)

In this case, a view can control another view. Say if you click on a menu from sidebar, it will load the respective content in Content area.

Logic to handle this will be put in Component class and UI portion code resides inside Component’s HTML & CSS.

How to create Component in Angular?

By default, App component gets created when new Angular project is created. If you expand the app folder under src folder, you can see default app source files created.

Angular Module

You can also create individual components once after new project has been created using one of below commands:

ng generate component <Component Name>

ng g component <Component Name>

ng g c <Component Name>

Angular Component Structure

app.component.html (HTML View):

UI code (View) goes within app.component.html. The UI controls events are handled in Logic class / code behind class (app.component.ts).

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
</div>
<h2>Here are some links to help you start: </h2>
<ul>
  <li>
    <h2><a target="_blank" rel="noopener" href="https://angular.io/tutorial">Tour of Heroes</a></h2>
  </li>
  <li>
    <h2><a target="_blank" rel="noopener" href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a></h2>
  </li>
  <li>
    <h2><a target="_blank" rel="noopener" href="https://blog.angular.io/">Angular blog</a></h2>
  </li>
</ul>

app.component.css (CSS Style):

CSS defined within app.component.css will be applied only for app.component.html

div{
    border: 1px solid red;
    margin: 5px;
}

app.component.ts (Controller):

This is called code behind page, that takes care the logical portion of component. Decorator / Meta data declared just above the class unites the HTML, CSS and Selector with a Component Class.

Selector <app-root> can be used inside any component of your application which will be replaced with app.component.html and the logic will be handled by app.component.ts respectively.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Hello World App';
}

app.component.spec.ts (Test Class):

Component spec file is a unit test for app.component.ts. The convention for Angular applications is to have a .spec.ts file for each .ts file. They are run using the Jasmine javascript test framework through the Karma task runner when you run the ng test command.

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  });

  it(`should have as title 'AngularBasics'`, () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app.title).toEqual('AngularBasics');
  });

  it('should render title in a h1 tag', () => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain('Welcome to AngularBasics!');
  });
});

Putting all together

A component (component.ts) comprises of UI (component.html), CSS (component.css) and Test class (component.specs.ts). And component class has a decorator that defines the selector and what the UI and CSS files are.