Creating an Angular Component
Creating components is a core concept in Angular because components are the building blocks of any Angular application.
🔹 What is an Angular Component?
A component in Angular controls a view (HTML template) and contains logic to support that view (written in a TypeScript class).
It typically consists of:
- A
.ts
file (logic) - A
.html
file (template) - A
.css
or.scss
file (styling)
🔧 How to Create a Component
✅ Using Angular CLI (recommended)
ng generate component component-name
# OR
ng g c component-name
For example:
ng g c user-profile
This creates a folder like this:
src/app/user-profile/
├── user-profile.component.ts ← component logic
├── user-profile.component.html ← template
├── user-profile.component.css ← styles
├── user-profile.component.spec.ts ← test file
🧱 Anatomy of a Component
user-profile.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-user-profile',
templateUrl: './user-profile.component.html',
styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent {
userName = 'John Doe';
}
user-profile.component.html
<h2>User Profile</h2>
<p>Welcome, {{ userName }}!</p>
💡 Using the Component in Another Template
If you want to include this component in another component’s HTML:
<app-user-profile></app-user-profile>
Angular knows about this because the component is declared in a module, typically in app.module.ts
.
🧠Summary
- Use
ng generate component
to create components quickly. - Each component has a selector, template, and logic.
- You can nest components by using their selectors in other components' templates.
Comments
Post a Comment