Angular Components

Angular Components

Components are the fundamental building blocks of any Angular application.

Every Angular app has at least one root component (usually AppComponent), and typically branches out into a massive tree of child components.

A component encapsulates a piece of the user interface, complete with its own dedicated logic and styling.


Generating a Component

While you can create a component manually, it requires creating four separate files and updating the App Module.

The Angular CLI makes this incredibly easy with the generate command.

In your terminal, you simply run ng generate component followed by the desired component name.

Generate Component CLI:

# This creates a new folder named 'header' containing the necessary files
ng generate component header

Shorthand syntax for the exact same command:

ng g c header


The Component Files

When you run the generate command, the CLI creates a dedicated folder holding four distinct files:

  1. header.component.ts: The TypeScript file containing your application logic.
  2. header.component.html: The HTML template dictating the visual structure.
  3. header.component.css: The scoped stylesheet that applies CSS exclusively to this component.
  4. header.component.spec.ts: A testing file used for automated unit tests.

The @Component Decorator

If you open the .ts file, you will notice a special @Component decorator placed directly above the class definition.

This decorator is what magically transforms a standard TypeScript class into an Angular component.

It contains metadata that tells Angular where to find the component's HTML and CSS files.

The Component Decorator:

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

@Component({ selector: 'app-header', // The custom HTML tag used to insert this component templateUrl: './header.component.html', styleUrls: ['./header.component.css'] }) export class HeaderComponent { welcomeText = 'Welcome to the Header!'; }


Using the Component

To display your new component on the screen, you use its defined selector as a custom HTML tag.

If you insert <app-header></app-header> into your main app.component.html file, the header will render flawlessly!


Exercise 1 of 2

?

What is the shorthand CLI command used to generate a brand new component named 'footer'?

Exercise 2 of 2

?

Which metadata property inside the @Component decorator defines the custom HTML tag used to insert the component?