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:

  1. A .ts file (logic)
  2. A .html file (template)
  3. 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

Popular posts from this blog

Car Wash System vb.net

C# Windows Form : PetCare

Face recognition using EmguCV 3.0 and typing pattern recognition