0
0
Angularframework~5 mins

Component decorator and metadata in Angular

Choose your learning style9 modes available
Introduction

The Component decorator tells Angular that a class is a component. It also gives extra information (metadata) about how the component should work and look.

When you want to create a new UI part in your Angular app.
When you need to define the HTML and CSS for a piece of your app.
When you want to connect a TypeScript class to a template and styles.
When you want Angular to manage and display a part of your app.
When you want to add metadata like selector, template, and styles to a class.
Syntax
Angular
@Component({
  selector: 'app-name',
  templateUrl: './app-name.component.html',
  styleUrls: ['./app-name.component.css']
})
export class AppNameComponent {
  // component logic here
}

The @Component decorator is placed just above the class.

The object inside @Component({ ... }) holds metadata like selector, template, and styles.

Examples
A simple component with inline HTML template.
Angular
@Component({
  selector: 'app-hello',
  template: '<h1>Hello World!</h1>'
})
export class HelloComponent {}
Component using external HTML and CSS files.
Angular
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent {}
Component with inline styles inside the decorator.
Angular
@Component({
  selector: 'app-button',
  template: '<button>Click me</button>',
  styles: ['button { color: blue; }']
})
export class ButtonComponent {}
Sample Program

This component shows a heading and a paragraph with some styles. The selector app-greeting is used to place this component in HTML.

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

@Component({
  selector: 'app-greeting',
  template: `<h2>Welcome to Angular!</h2><p>This is a simple component.</p>`,
  styles: [`h2 { color: green; } p { font-style: italic; }`]
})
export class GreetingComponent {}
OutputSuccess
Important Notes

The selector is the HTML tag you use to add the component in your app.

You can use either template for inline HTML or templateUrl for an external file.

Similarly, use styles for inline CSS or styleUrls for external CSS files.

Summary

The @Component decorator marks a class as an Angular component.

Metadata inside the decorator tells Angular how to display and style the component.

Use selector, template/templateUrl, and styles/styleUrls to define your component's look and usage.