0
0
AngularConceptBeginner · 3 min read

What is Component Decorator in Angular: Explanation and Example

In Angular, the @Component decorator is a special function that marks a class as an Angular component and provides metadata about how the component should be processed, instantiated, and used at runtime. It tells Angular what HTML template and styles to use for that component and how to display it in the app.
⚙️

How It Works

The @Component decorator works like a label you put on a class to tell Angular, "This class is a component." It adds extra information called metadata that describes the component's template (HTML), styles (CSS), and other settings. Think of it like putting a name tag on a person that also says what job they do and how they should behave.

When Angular sees this decorator, it knows to create and display the component's view in the app. It connects the class logic with the HTML and CSS so they work together. This is similar to how a recipe card tells a cook what ingredients to use and how to prepare a dish.

💻

Example

This example shows a simple Angular component using the @Component decorator. It defines a title and displays it in the browser.

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

@Component({
  selector: 'app-hello',
  template: `<h1>{{ title }}</h1>`,
  styles: [`h1 { color: teal; font-family: Arial, sans-serif; }`]
})
export class HelloComponent {
  title = 'Hello, Angular!';
}
Output
<h1 style="color: teal; font-family: Arial, sans-serif;">Hello, Angular!</h1>
🎯

When to Use

Use the @Component decorator whenever you want to create a new UI element in your Angular app. Components are the building blocks of Angular applications, each controlling a part of the screen.

For example, use it to make a navigation bar, a user profile card, or a list of items. It helps organize your app into small, reusable pieces that are easier to build and maintain.

Key Points

  • @Component marks a class as an Angular component.
  • It provides metadata like selector, template, and styles.
  • Angular uses this metadata to render the component in the app.
  • Every UI part in Angular is usually a component decorated this way.

Key Takeaways

The @Component decorator tells Angular a class is a UI component with its own template and styles.
It connects the class logic with HTML and CSS to display content in the app.
Use @Component to create reusable and organized parts of your Angular application.
The selector property defines how to use the component in HTML.
Templates and styles inside @Component control the component's look and structure.