An Angular component consists of:
๐ Template (.html
) – Defines the UI layout
๐ Styles (.css
or .scss
) – Adds styles to the component
๐ Class (.ts
) – Contains logic and data binding
Angular CLI provides a command to generate components quickly.
Run the following command in your terminal:
OR (shorter version)
ng g c my-component
This will create:
๐ src/app/my-component/
Every component has a selector that can be used in other components or pages.
Find the selector inside my-component.component.ts
:
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
Now, use this selector inside app.component.html
:
<app-my-component></app-my-component>
Modify my-component.component.ts
to add data:
import { Component } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent {
title: string = 'Hello from MyComponent!';
}
Update my-component.component.html
:
<h2>{{ title }}</h2>
Angular allows component-specific styling.
Modify my-component.component.css
:
h2 {
color: blue;
text-align: center;
}
Angular components communicate using @Input and @Output decorators.
Example:
Modify my-component.component.ts
:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent {
@Input() message!: string;
}
Now, pass data from app.component.html
:
<app-my-component [message]="'Hello from Parent Component!'"></app-my-component>
โ๏ธ Components are the foundation of Angular applications
โ๏ธ Created a new component using Angular CLI
โ๏ธ Added data binding to display dynamic content
โ๏ธ Styled the component
โ๏ธ Passed data between components
By mastering components, you can structure and scale your Angular projects efficiently! ๐