Angular Components

Read one Angular interview question at a time, then flip for the complete explanation, example, and code.

0/63 Known filtered set
Level
Read Full Guide Question: 1 of 63

Angular Interview Questions · Angular Components Companion Article

Angular Components

Angular applications are built from components. A component represents a specific part of the user interface and contains the logic, HTML structure, and styling needed for that part of the application. A small application may contain only a few components, while a large business application can contain hundreds of components organized into a component tree. This chapter explains how Angular components are structured, configured with the @Component decorator, given templates and styles, and combined into a component tree to build real Angular user interfaces.

Component Basics

For example, an e-commerce page might contain separate components for:

  • Header
  • Navigation menu
  • Product list
  • Product card
  • Search box
  • Shopping cart
  • Footer

Breaking an application into components makes the code easier to understand, test, maintain, and reuse.

An Angular component is a TypeScript class that Angular uses to control a portion of the webpage.

A component normally contains three main parts:

  1. Component class — stores data and application logic.
  2. Template — defines what appears in the browser.
  3. Styles — control the appearance of the component.

A basic component may look like this:

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

@Component({
  selector: 'app-welcome',
  template: `<h2>Welcome to Angular</h2>`
})
export class WelcomeComponent {
}

Here:

  • WelcomeComponent is the component class.
  • @Component() tells Angular that the class is a component.
  • selector defines how the component can be used in another template.
  • template defines the component's HTML.

The component can then be used using its selector:

HTML
<app-welcome></app-welcome>

When Angular finds this element, it renders the template associated with WelcomeComponent.

Why Angular Uses Components

Without components, an entire application could become one large collection of HTML and TypeScript code.

Components divide the application into smaller responsibilities.

For example:

Text
Application
│
├── Header
├── Sidebar
├── Product List
│   ├── Product Card
│   ├── Product Card
│   └── Product Card
└── Footer

Each component can focus on one job.

A ProductCardComponent, for example, should normally handle the presentation and behavior of a product card rather than contain unrelated code for authentication, navigation, or application configuration.

This separation makes large Angular applications easier to manage.

Creating Components

A component can be created manually or generated using Angular CLI.

Creating a Component with Angular CLI

A common command is:

Bash
ng generate component product-card

The shorter form is:

Bash
ng g c product-card

Angular CLI creates the files required by the component according to the project's configuration.

A generated component commonly includes files such as:

Text
product-card/
├── product-card.ts
├── product-card.html
├── product-card.css
└── product-card.spec.ts

Exact generated filenames and files may vary depending on CLI configuration and options.

Creating a Component Manually

A component can also be created directly.

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

@Component({
  selector: 'app-profile',
  templateUrl: './profile.html',
  styleUrl: './profile.css'
})
export class ProfileComponent {
}

Angular needs the component decorator so that it knows how the class should participate in the user interface.

Choosing Good Component Names

Component names should describe their responsibility clearly.

Good examples:

Text
LoginComponent
ProductCardComponent
UserProfileComponent
OrderHistoryComponent
SearchBarComponent

Less useful names include:

Text
DataComponent
NewComponent
TestComponent
Component1

Clear component names become increasingly important as an Angular application grows.

Component Decorator

The @Component() decorator provides Angular with information about a component.

Example:

TypeScript
@Component({
  selector: 'app-user',
  templateUrl: './user.html',
  styleUrl: './user.css'
})
export class UserComponent {
}

The decorator is placed immediately before the component class.

Angular reads the decorator metadata to determine things such as:

  • Which selector identifies the component
  • Which template belongs to it
  • Which styles belong to it
  • Which dependencies or components it imports
  • Whether it is a standalone component

The decorator comes from Angular's core package:

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

Component Metadata

The configuration inside @Component() is called component metadata.

Example:

TypeScript
@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.html',
  styleUrl: './dashboard.css'
})
export class DashboardComponent {
}

The metadata connects the TypeScript class with the visual part of the component.

Common metadata properties include:

PropertyPurpose
selectorDefines how the component is referenced
templateDefines inline HTML
templateUrlLoads HTML from an external file
stylesDefines inline component CSS
styleUrlReferences a component stylesheet
styleUrlsReferences multiple stylesheets where applicable
importsMakes dependencies available to a standalone component
standaloneIndicates standalone component configuration where explicitly used
providersDefines services/providers available in the component injector
changeDetectionConfigures the component's change-detection strategy

Not every component needs every property.

Use only the metadata required by that component.

Component Class

The component class contains the data and behavior used by the component.

Example:

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

@Component({
  selector: 'app-user',
  template: `
    <h2>{{ name }}</h2>
    <button (click)="changeName()">Change Name</button>
  `
})
export class UserComponent {
  name = 'Rahul';

  changeName(): void {
    this.name = 'Amit';
  }
}

The class contains:

TypeScript
name = 'Rahul';

This is component data.

It also contains:

TypeScript
changeName(): void {
  this.name = 'Amit';
}

This is component behavior.

The template can access public members of the component class.

What Usually Belongs in a Component Class?

A component class may contain:

  • Properties
  • Methods
  • Event handling logic
  • UI state
  • Injected dependencies
  • Lifecycle logic
  • Data prepared for the template

For example:

TypeScript
export class CounterComponent {
  count = 0;

  increment(): void {
    this.count++;
  }

  decrement(): void {
    this.count--;
  }
}

The template could use these members:

HTML
<h2>{{ count }}</h2>

<button (click)="increment()">+</button>
<button (click)="decrement()">-</button>

Avoid Putting Everything in a Component

A component should not become responsible for every part of the application.

For example, complicated HTTP communication, reusable business rules, caching logic, and application-wide state may belong in services or other dedicated layers rather than directly inside a UI component.

Keeping component responsibilities focused improves maintainability.

Component Template

The template defines the component's user interface.

A template uses HTML together with Angular template features.

Example:

HTML
<h1>{{ title }}</h1>

<p>Welcome, {{ username }}</p>

<button (click)="logout()">Logout</button>

The template can interact with data from the component class.

For example:

TypeScript
export class DashboardComponent {
  title = 'Dashboard';
  username = 'Dattatray';

  logout(): void {
    console.log('User logged out');
  }
}

Angular connects the class and template.

Template Expressions

Values can be displayed using interpolation:

HTML
<h2>{{ productName }}</h2>

If the component contains:

TypeScript
productName = 'Laptop';

Angular displays:

Text
Laptop

Templates can also use bindings, events, control-flow features, pipes, child components, and other Angular template functionality.

External Component Templates

For larger templates, HTML is usually placed in a separate file.

Component:

TypeScript
@Component({
  selector: 'app-login',
  templateUrl: './login.html'
})
export class LoginComponent {
}

Template:

HTML
<h2>Login</h2>

<label>Email</label>
<input type="email">

<label>Password</label>
<input type="password">

<button>Login</button>

External templates keep TypeScript and HTML separate, which is often easier to maintain when the user interface becomes large.

Component Styles

Angular components can contain styles specifically associated with their templates.

Example:

CSS
h2 {
  font-size: 24px;
}

button {
  padding: 8px 16px;
}

Component:

TypeScript
@Component({
  selector: 'app-login',
  templateUrl: './login.html',
  styleUrl: './login.css'
})
export class LoginComponent {
}

Component styles are useful because each component can maintain its own presentation rules.

Component Styles vs Global Styles

Angular applications commonly contain both component-level and global styles.

Component Styles

Use component styles for UI rules specific to one component.

Example:

CSS
.product-card {
  padding: 20px;
  border: 1px solid #ddd;
}

Global Styles

Use global styles for application-wide design rules such as:

  • Page background
  • Typography
  • CSS resets
  • Shared utility classes
  • Application-wide variables
  • Common layout rules

A clear styling strategy prevents unrelated components from becoming tightly coupled through CSS.

Inline Templates

Instead of using an external HTML file, HTML can be written directly inside the component decorator.

Example:

TypeScript
@Component({
  selector: 'app-message',
  template: `<p>Angular components are reusable.</p>`
})
export class MessageComponent {
}

For multiline HTML, template literals can be used:

TypeScript
@Component({
  selector: 'app-profile',
  template: `
    <section>
      <h2>User Profile</h2>
      <p>Name: {{ name }}</p>
      <p>Role: {{ role }}</p>
    </section>
  `
})
export class ProfileComponent {
  name = 'Rahul';
  role = 'Developer';
}

When Inline Templates Are Useful

Inline templates work well for components containing very small amounts of markup.

Examples include:

  • Simple labels
  • Small icons
  • Simple status components
  • Tiny reusable UI elements
  • Demonstration components

For a large user interface, external templates are generally easier to read and maintain.

Inline Styles

Styles can also be placed directly inside component metadata.

Example:

TypeScript
@Component({
  selector: 'app-alert',
  template: `<p class="message">Operation completed.</p>`,
  styles: [`
    .message {
      font-weight: bold;
      padding: 10px;
    }
  `]
})
export class AlertComponent {
}

This keeps the TypeScript, HTML, and styles in one file.

It may be useful for very small components.

Inline Styles vs External Styles

Inline Styles

Suitable when:

  • The component is very small
  • Only a few styles are required
  • Keeping everything together improves readability

External Styles

Suitable when:

  • The stylesheet is large
  • Multiple CSS rules are required
  • Designers frequently work with styles
  • Separation makes the component easier to maintain

There is no need to force every component to use the same approach. The choice should depend on the size and responsibility of the component.

Component Selector

The selector determines how Angular identifies a component in a template.

Example:

TypeScript
@Component({
  selector: 'app-product-card',
  template: `<p>Product Card</p>`
})
export class ProductCardComponent {
}

The component can be used as:

HTML
<app-product-card></app-product-card>

The browser may initially treat app-product-card as a custom element, and Angular associates it with the corresponding component.

Selector Naming

A project-specific prefix is commonly used.

Example:

Text
app-header
app-footer
app-product
app-user-profile

The prefix helps distinguish application components from normal HTML elements and components from other libraries.

Keep Selectors Descriptive

Prefer:

Text
app-shopping-cart
app-product-details
app-user-profile

instead of vague selectors such as:

Text
app-box
app-data
app-item2

A selector should indicate what the component represents.

Standalone Components

Modern Angular development supports standalone components, allowing components to declare their own template dependencies directly rather than requiring every component to be declared through an NgModule.

Example:

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

@Component({
  selector: 'app-home',
  standalone: true,
  template: `<h1>Home</h1>`
})
export class HomeComponent {
}

Standalone architecture can reduce module-related boilerplate and makes component dependencies easier to see.

Importing Another Standalone Component

Suppose there is a child component:

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

@Component({
  selector: 'app-user-card',
  standalone: true,
  template: `<p>User Card</p>`
})
export class UserCardComponent {
}

A parent component can import it:

TypeScript
import { Component } from '@angular/core';
import { UserCardComponent } from './user-card';

@Component({
  selector: 'app-dashboard',
  standalone: true,
  imports: [UserCardComponent],
  template: `
    <h1>Dashboard</h1>
    <app-user-card></app-user-card>
  `
})
export class DashboardComponent {
}

The important relationship is:

Text
DashboardComponent
        │
        └── imports UserCardComponent

The dashboard can then use the child component's selector in its template.

Why Standalone Components Are Useful

Standalone components can make dependencies more explicit.

A developer can inspect:

TypeScript
imports: [UserCardComponent]

and immediately understand that the component depends on UserCardComponent.

They are particularly useful for:

  • New Angular applications
  • Reusable UI components
  • Feature organization
  • Lazy-loaded application areas
  • Reducing unnecessary module configuration

Understanding NgModule-based applications is still valuable because many existing Angular projects use them.

Component Tree

Angular applications naturally form a hierarchy known as a component tree.

Consider an online store:

Text
AppComponent
│
├── HeaderComponent
│   ├── LogoComponent
│   └── SearchComponent
│
├── ProductListComponent
│   ├── ProductCardComponent
│   ├── ProductCardComponent
│   └── ProductCardComponent
│
├── CartComponent
│   └── CartItemComponent
│
└── FooterComponent

AppComponent is near the top of the hierarchy.

It contains several child components.

Some of those child components contain their own children.

Parent and Child Components

If one component is placed inside another component's template, a parent-child relationship is created.

Example:

HTML
<app-header></app-header>

<app-product-list></app-product-list>

<app-footer></app-footer>

If this template belongs to AppComponent, then:

Text
AppComponent
├── HeaderComponent
├── ProductListComponent
└── FooterComponent

AppComponent is the parent.

The other components are children.

Nested Components

A nested component is a component used inside another component.

Suppose an application contains a reusable product card.

TypeScript
@Component({
  selector: 'app-product-card',
  standalone: true,
  template: `
    <div class="product">
      <h3>Wireless Mouse</h3>
      <p>₹799</p>
    </div>
  `
})
export class ProductCardComponent {
}

It can be placed inside a product-list component:

TypeScript
import { Component } from '@angular/core';
import { ProductCardComponent } from './product-card';

@Component({
  selector: 'app-product-list',
  standalone: true,
  imports: [ProductCardComponent],
  template: `
    <h2>Products</h2>
    <app-product-card></app-product-card>
    <app-product-card></app-product-card>
  `
})
export class ProductListComponent {
}

The structure becomes:

Text
ProductListComponent
│
├── ProductCardComponent
└── ProductCardComponent

The same component definition can therefore be reused multiple times.

Practical Component Example

Consider a dashboard containing three sections:

Text
Dashboard
├── Profile
├── Notifications
└── Recent Orders

Each feature can become a component.

Profile Component

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

@Component({
  selector: 'app-profile',
  standalone: true,
  template: `
    <section>
      <h2>{{ name }}</h2>
      <p>{{ role }}</p>
    </section>
  `
})
export class ProfileComponent {
  name = 'Amit';
  role = 'Software Developer';
}

Notification Component

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

@Component({
  selector: 'app-notifications',
  standalone: true,
  template: `
    <section>
      <h2>Notifications</h2>
      <p>You have {{ notificationCount }} new notifications.</p>
    </section>
  `
})
export class NotificationsComponent {
  notificationCount = 3;
}

Dashboard Component

TypeScript
import { Component } from '@angular/core';
import { ProfileComponent } from './profile';
import { NotificationsComponent } from './notifications';

@Component({
  selector: 'app-dashboard',
  standalone: true,
  imports: [
    ProfileComponent,
    NotificationsComponent
  ],
  template: `
    <h1>Dashboard</h1>
    <app-profile></app-profile>
    <app-notifications></app-notifications>
  `
})
export class DashboardComponent {
}

This approach is easier to maintain than placing the entire dashboard interface and logic inside one large component.

Component Responsibility

One of the most useful design principles in Angular is giving each component a clear responsibility.

For example:

Text
ProductListComponent

should mainly manage the product-list user interface.

Text
ProductCardComponent

should present an individual product.

Text
CartComponent

should represent the shopping-cart interface.

Problems begin when one component starts handling unrelated responsibilities.

For example, a single component containing:

  • Authentication
  • Product listing
  • Cart management
  • User settings
  • Payment logic
  • Navigation
  • Reporting

will usually become difficult to maintain.

Breaking such functionality into appropriate components and services creates clearer boundaries.

Large Components vs Small Components

There is no rule saying that every few lines of HTML must become a separate component.

Creating too many tiny components can also make an application unnecessarily complicated.

Create a separate component when the UI section:

  • Has its own responsibility
  • Is reused
  • Has independent behavior
  • Has significant markup
  • Needs independent testing
  • Represents a meaningful application concept

For example, a complete reusable product card is a strong component candidate.

A single <span> used only once usually does not need its own component.

Reusable Components

One major benefit of component architecture is reuse.

Consider:

HTML
<app-product-card></app-product-card>

Instead of duplicating product markup across many pages, the application can reuse the same component.

A properly designed reusable component can later receive different data and react to different events.

This leads naturally to Angular concepts such as:

  • Inputs
  • Outputs
  • Event binding
  • Component communication

These concepts allow the same component structure to work with different values.

Component Composition

Angular encourages composition.

Instead of building one huge component, an interface can be assembled from smaller components.

For example:

Text
ProductPageComponent
├── ProductGalleryComponent
├── ProductInformationComponent
├── PriceComponent
├── AddToCartComponent
├── ReviewListComponent
└── RelatedProductsComponent

This approach provides several advantages:

  • Individual components are easier to understand.
  • Changes affect smaller areas.
  • Components can be tested separately.
  • Reusable sections can be shared.
  • Teams can work on different components independently.

Component File Organization

For a small component, related files may be grouped together.

Text
product-card/
├── product-card.ts
├── product-card.html
├── product-card.css
└── product-card.spec.ts

For more complicated features, components can be grouped according to the application domain.

Example:

Text
products/
├── product-list/
├── product-card/
├── product-details/
└── product-search/

Grouping components by feature can make large applications easier to navigate than keeping unrelated components in a single folder.

Common Component Mistakes

1. Creating One Huge Component

Avoid placing an entire page's business and presentation logic into one extremely large component.

Break meaningful sections into smaller components where appropriate.

2. Creating Components for Every HTML Element

Componentization should improve the architecture, not create unnecessary complexity.

Do not create a component simply because an element exists.

3. Using Vague Component Names

Avoid:

Text
BoxComponent
Main2Component
DataComponent
TempComponent

Prefer names that describe business or UI meaning.

4. Putting Too Much Business Logic in Components

Components primarily represent UI behavior and presentation.

Complex reusable business logic is often better handled through services or other dedicated application layers.

5. Forgetting Component Dependencies

When a component uses another component, directive, or pipe, the required dependency must be available in that component's compilation context.

In standalone components, dependencies are commonly added through the component's imports.

6. Using Incorrect Selectors

If the component selector is:

TypeScript
selector: 'app-user-profile'

use:

HTML
<app-user-profile></app-user-profile>

Using a different element name will not refer to that component.

7. Duplicating UI Instead of Reusing Components

If the same meaningful interface appears repeatedly, consider whether it should become a reusable component rather than copying its markup to several pages.

Component Design Example: Bad vs Better

A page containing everything in one component might look conceptually like:

Text
DashboardComponent
├── Header logic
├── Search logic
├── Profile logic
├── Product logic
├── Notification logic
├── Order logic
└── Footer logic

A better structure could be:

Text
DashboardComponent
├── HeaderComponent
├── SearchComponent
├── ProfileComponent
├── ProductListComponent
├── NotificationsComponent
├── OrderHistoryComponent
└── FooterComponent

The second structure gives each important UI section a clearer responsibility.

How Angular Renders a Component

At a high level, the process can be understood as:

Text
Component Class
      │
      ▼
@Component Metadata
      │
      ├── Selector
      ├── Template
      └── Styles
      │
      ▼
Angular
      │
      ▼
Rendered User Interface

The class supplies data and behavior.

The metadata tells Angular how the component is configured.

The template describes the HTML.

The styles control presentation.

Angular combines these pieces and renders the result.

Component Development Workflow

A practical component-development process is:

Text
Identify UI responsibility
        ↓
Create component
        ↓
Define selector
        ↓
Create template
        ↓
Add component data
        ↓
Add event handling
        ↓
Add styles
        ↓
Add required imports
        ↓
Use component in parent
        ↓
Test component behavior

Thinking about responsibility before creating the component prevents unnecessary fragmentation.

Example: Converting HTML Into Components

Suppose a page initially contains:

HTML
<header>
  ...
</header>

<section class="profile">
  ...
</section>

<section class="orders">
  ...
</section>

<footer>
  ...
</footer>

If these sections have independent responsibilities, the application might evolve into:

HTML
<app-header></app-header>

<app-profile></app-profile>

<app-order-history></app-order-history>

<app-footer></app-footer>

The page then becomes a composition of components rather than one large block of markup.

Components and Maintainability

Imagine the same user profile appears on:

  • Dashboard
  • Account page
  • Admin page

Without a reusable component, the same HTML and logic might be copied into several files.

If the design changes, developers may have to update every copy.

With a reusable component:

HTML
<app-user-profile></app-user-profile>

the implementation can be maintained in one place and reused wherever appropriate.

This is one of the practical reasons component-based architecture works well for large applications.

Component Testing

Component architecture also improves testability.

A focused component can be tested independently for behavior such as:

  • Whether the correct information is displayed
  • Whether a button triggers the expected action
  • Whether conditional content appears correctly
  • Whether inputs affect rendering correctly
  • Whether emitted events contain expected values

Smaller components with clear responsibilities are generally easier to test than one component containing many unrelated features.

When Should You Create a New Component?

Consider creating a component when a piece of UI:

  • Appears in multiple places
  • Represents an independent feature
  • Has its own behavior
  • Has substantial markup
  • Can logically be named
  • Needs independent maintenance
  • Needs independent testing

Examples:

Text
NavbarComponent
LoginFormComponent
ProductCardComponent
PaginationComponent
UserAvatarComponent
ShoppingCartComponent
NotificationPanelComponent

Do not create components solely to increase the number of files in the project.

Component Naming Guidelines

A useful naming pattern is:

Text
Feature + Component

Examples:

Text
UserProfileComponent
ProductListComponent
ShoppingCartComponent
PaymentSummaryComponent
OrderHistoryComponent

Selectors can use corresponding kebab-case names:

Text
app-user-profile
app-product-list
app-shopping-cart
app-payment-summary
app-order-history

Consistent naming makes the component structure easier for other developers to understand.

Component Concepts at a Glance

ConceptMeaning
ComponentReusable building block of an Angular UI
Component classContains data and behavior
@ComponentDecorator defining Angular component metadata
MetadataConfiguration describing the component
SelectorIdentifies the component in templates
TemplateDefines the component's HTML
StylesDefine component presentation
Inline templateHTML stored in component metadata
External templateHTML stored in a separate file
Inline stylesCSS stored directly in component metadata
Standalone componentComponent that manages dependencies without requiring declaration in an NgModule
Parent componentComponent containing another component
Child componentComponent used inside another component
Component treeHierarchical structure of Angular components
Nested componentComponent rendered inside another component
Component compositionBuilding larger interfaces from smaller components

Practical Rules to Remember

  • Build Angular user interfaces from components with clear responsibilities.
  • Keep component names meaningful.
  • Keep selectors consistent with project naming conventions.
  • Use external templates when markup becomes large.
  • Inline templates are convenient for small components.
  • Keep component-specific CSS close to the component where appropriate.
  • Avoid turning one component into the entire application.
  • Do not split trivial HTML into unnecessary components.
  • Prefer reusable components for repeated UI patterns.
  • Understand parent-child relationships before designing complex screens.
  • Keep standalone component dependencies explicit.
  • Organize components by application feature as projects grow.
  • Move reusable or complex non-UI logic out of components when another application layer is more appropriate.

Real-World Example

Consider an online shopping application.

A product page might use:

Text
ProductDetailsPageComponent
│
├── HeaderComponent
├── BreadcrumbComponent
├── ProductGalleryComponent
├── ProductDetailsComponent
│   ├── ProductPriceComponent
│   └── AddToCartComponent
├── ReviewListComponent
│   └── ReviewCardComponent
├── RelatedProductsComponent
│   └── ProductCardComponent
└── FooterComponent

This illustrates an important Angular design idea:

A page does not need to be one component. A page can be a composition of multiple components, each responsible for a meaningful part of the interface.

As the application grows, this structure makes features easier to locate, modify, reuse, and test.

Key Takeaways

Angular components connect TypeScript logic, HTML templates, styles, and metadata into reusable user-interface building blocks.

The most important concepts to understand are:

  • A component is represented by a TypeScript class.
  • @Component() supplies Angular-specific metadata.
  • The selector determines how the component is referenced.
  • The template defines the displayed interface.
  • Styles define the component's presentation.
  • Templates and styles can be inline or external.
  • Standalone components can manage their dependencies directly.
  • Components can contain other components.
  • Parent-child relationships form a component tree.
  • Reusable, focused components make Angular applications easier to maintain.

Once components are clear, topics such as data binding, input/output communication, lifecycle hooks, content projection, signals, dependency injection, routing, and change detection become much easier to understand because they all operate around Angular's component model.

Question Hint