What is Component Decorator in Angular: Explanation and Example
@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.
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!'; }
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, andstyles. - Angular uses this metadata to render the component in the app.
- Every UI part in Angular is usually a component decorated this way.