WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Angular · Basic · question 3 of 100

What are Angular components and how do they interact with each other?

📕 Buy this interview preparation book: 100 Angular questions & answers — PDF + EPUB for $5

Angular components are the primary building blocks of Angular applications. They are essential for structuring the application, organizing its behavior, and managing data. Components are basically classes with HTML templates and styles that define the appearance, actions, and data handling of a specific part of a web page. A component is responsible for one part of the application UI, and multiple components can be combined to create complex and feature-rich applications.

The interaction between Angular components can be explained in the following ways:

1. **Component hierarchy**: Components are organized in a parent-child hierarchy, where a parent component can contain one or more child components. A typical Angular application contains one root component, usually called ‘AppComponent‘, that hosts all other components. This hierarchy helps manage data flow and communication between components, and also promotes separation of concerns.

2. **Input and Output**: One common method for components to interact is through _inputs_ and _outputs_. Parent components can pass data to a child component through inputs, and child components can emit events to notify their parent components about changes through outputs. This communication technique allows for the unidirectional flow of data, which makes it easier to track and understand the flow of data within the application.

For example, consider a parent component that displays an array of items and a child component for editing a single item. The parent component can pass the item to the child component through an input, and the child component can notify the parent component about changes through an output:


// parent.component.ts

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

@Component({
  selector: 'app-parent',
  template: `
    <app-child [item]="selectedItem" (itemChange)="onItemChange($event)"></app-child>
  `
})
export class ParentComponent {
  selectedItem = {
    id: 1,
    name: 'Example Item'
  };

  onItemChange(updatedItem) {
    console.log('Item updated:', updatedItem);
  }
}
// child.component.ts

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    <button (click)="updateItem()">Update Item</button>
  `
})
export class ChildComponent {
  @Input() item: any;
  @Output() itemChange = new EventEmitter<any>();

  updateItem() {
    this.item.name = 'Updated Item';
    this.itemChange.emit(this.item);
  }
}

3. **Services**: Another way for Angular components to interact is by using shared services. Services are singletons that can be injected into components via Angular’s dependency injection system, and they can be used to store and share data, or encapsulate complex logic. When components need to communicate with each other, a service can act as a mediator or a centralized store, making it easier to manage state and coordination between various components.

For example, consider a service called ‘DataService‘ that retrieves and stores data for a list of items:

// data.service.ts

import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class DataService {
  private items = [
    { id: 1, name: 'Item 1' },
    { id: 2, name: 'Item 2' }
  ];

  getItems() {
    return this.items;
  }

  updateItem(item) {
    const index = this.items.findIndex(i => i.id === item.id);
    this.items[index] = item;
  }
}

Two components, ‘ListComponent‘ and ‘EditComponent‘, can now communicate with each other by using the shared ‘DataService‘:

// list.component.ts

import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-list',
  template: `
    <ul>
      <li *ngFor="let item of items">{{ item.name }}</li>
    </ul>
  `
})
export class ListComponent {
  items = this.dataService.getItems();

  constructor(private dataService: DataService) {}
}
// edit.component.ts

import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-edit',
  template: `
    <button (click)="updateItem()">Update Item</button>
  `
})
export class EditComponent {
  selectedItem = {
    id: 1,
    name: 'Example Item'
  };

  constructor(private dataService: DataService) {}

  updateItem() {
    this.selectedItem.name = 'Updated Item';
    this.dataService.updateItem(this.selectedItem);
  }
}

These are the main ways Angular components interact with each other. By leveraging component hierarchy, inputs and outputs, and shared services, you can create complex and maintainable Angular applications.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Angular interview — then scores it.
📞 Practice Angular — free 15 min
📕 Buy this interview preparation book: 100 Angular questions & answers — PDF + EPUB for $5

All 100 Angular questions · All topics