Discover how a simple decorator can turn messy code into neat, reusable building blocks!
Why Component decorator and metadata in Angular? - Purpose & Use Cases
Imagine building a web page by manually writing all the HTML, CSS, and JavaScript for each part, then trying to keep track of which styles and behaviors belong to which section.
Every time you want to change a button or a form, you have to hunt through your code to find and update it.
This manual approach is confusing and slow because your code gets messy and mixed up.
It's easy to make mistakes like changing the wrong element or breaking something else by accident.
Also, reusing parts of your page is hard without copying and pasting code everywhere.
The Component decorator in Angular lets you wrap HTML, CSS, and behavior together as one neat package called a component.
Metadata inside the decorator tells Angular how to use that component, like what HTML to show and what styles to apply.
This keeps your code organized, easy to reuse, and simple to update.
function createButton() {
const btn = document.createElement('button');
btn.textContent = 'Click me';
btn.style.color = 'blue';
btn.onclick = () => alert('Clicked!');
return btn;
}import { Component } from '@angular/core'; @Component({ selector: 'app-button', template: `<button (click)="onClick()">Click me</button>`, styles: [`button { color: blue; }`] }) export class ButtonComponent { onClick() { alert('Clicked!'); } }
It enables building clear, reusable, and self-contained UI parts that work together smoothly.
Think of a website's navigation bar as a component: it has its own look, links, and behavior all bundled together, so you can use it on many pages without rewriting code.
Manual UI code is hard to manage and reuse.
Component decorator bundles template, styles, and logic.
Metadata guides Angular to use components correctly.