NashTech Insights

Methods to Share Data Between Angular Components

Aanchal
Aanchal
Table of Contents
Sharing Data Between Angular Components

Introduction

In Angular applications, one of the most common challenges developers face is sharing data between different components. Angular provides several methods to facilitate this data sharing, allowing you to build efficient and modular applications. In this blog, we will explore various techniques to share data between Angular components.

1. Input and Output Properties

Input and output properties are a fundamental way to share data between parent and child components. These properties allow you to pass data from a parent component to a child component and emit events from the child component back to the parent component.

Parent Component

@Component({
  selector: 'app-parent',
  template: '<app-child [childData]="data" (childEvent)="handleChildEvent($event)"></app-child>'
})
export class ParentComponent {
  data = 'Data from Parent';
  handleChildEvent(dataFromChild) {
    console.log(dataFromChild);
  }
}

Child Component

@Component({
  selector: 'app-child',
  template: '{{ childData }} <button (click)="sendDataToParent()">Send Data to Parent</button>'
})
export class ChildComponent {
  @Input() childData: string;
  @Output() childEvent = new EventEmitter<string>();

  sendDataToParent() {
    this.childEvent.emit('Data from Child');
  }
}

2. Services

Angular services are another powerful way to share data between components. Services are singletons that can store and provide data to different parts of your application.

Data Service

@Injectable({
  providedIn: 'root'
})
export class DataService {
  sharedData: string;

  setSharedData(data: string) {
    this.sharedData = data;
  }

  getSharedData() {
    return this.sharedData;
  }
}

Components Using the Service

@Component({
  selector: 'app-component1',
  template: '<button (click)="setData()">Set Data</button>'
})
export class Component1 {
  constructor(private dataService: DataService) { }

  setData() {
    this.dataService.setSharedData('Shared Data');
  }
}

@Component({
  selector: 'app-component2',
  template: '{{ sharedData }}'
})
export class Component2 {
  sharedData: string;

  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.sharedData = this.dataService.getSharedData();
  }
}

3. RxJS Subjects

RxJS Subjects provide a flexible way to share data between components using observable streams. You can subscribe to these streams to receive updates when data changes.

Data Service with RxJS Subject

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

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private sharedDataSubject = new Subject<string>();
  sharedData$ = this.sharedDataSubject.asObservable();

  setSharedData(data: string) {
    this.sharedDataSubject.next(data);
  }
}

Component Using the RxJS Subject

@Component({
  selector: 'app-component3',
  template: '<div>{{ sharedData }}</div>'
})
export class Component3 implements OnInit {
  sharedData: string;

  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.dataService.sharedData$.subscribe(data => {
      this.sharedData = data;
    });
  }
}

4. @ViewChild and @ViewChildren

You can use @ViewChild and @ViewChildren decorators to access child components’ properties and methods from their parent components directly. This method is useful for sharing data in cases where child components need to communicate with their parent.

Conclusion

Sharing data between Angular components is a crucial aspect of building modular and maintainable applications. Depending on your specific use case, you can choose from a variety of methods, including Input and Output properties, services, RxJS Subjects, and @ViewChild/@ViewChildren. Understanding when and how to use each method will help you design effective and responsive Angular applications.

Finally, for more such updates and to read more about such topics, please follow our LinkedIn page Frontend Competency

Aanchal

Aanchal

Aanchal Agarwal is a Software Consultant at NashTech. Her practice area is web development. She is recognized as a multi-talented, multitasker, and adaptive to the different work environments. Her hobbies include watching movies, listening to music, and traveling. She likes to read books and explore new things.

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

%d bloggers like this: