Angular

    All Possible Ways to Share Data Between Components in Angular


    Introduction

    Data sharing becomes a common requirement in Angular components. The following list contains all available methods for data sharing in Angular:

    The function of @Input() and @Output() enables communication between parent and child components.

    The Input function enables data transmission between parent and child components.

    The child component can transmit data to the parent by utilizing the EventEmitter functionality through @Output().

    Example

    Parent Component:

    <app-child [message]="parentMessage" (childEvent)="receiveMessage($event)"></app-child> <p>From Child: {{ childMessage }}</p>export class AppComponent {parentMessage = "Hello from Parent";childMessage = "";receiveMessage(event: string) {this.childMessage = event;}}

     

    Child Component:

    export class ChildComponent {@Input() message!: string;@Output() childEvent = new EventEmitter<string>();sendMessage() {this.childEvent.emit("Hello from Child");}}<p>From Parent: {{ message }}</p><button (click)="sendMessage()">Send to Parent</button>

    Using a Shared Service (RxJS)

    For sharing data between unrelated components, use a service with BehaviorSubject.

    Example

    Shared Service:

    @Injectable({ providedIn: 'root' })export class SharedService {private messageSource = new BehaviorSubject<string>("Initial Message");currentMessage = this.messageSource.asObservable();changeMessage(message: string) {this.messageSource.next(message);}}

    Component A (Sender):

    this.sharedService.changeMessage("Hello from A");

    Component B (Receiver):

    this.sharedService.currentMessage.subscribe(message => console.log("Received:", message));

    Using a Shared Service with Subject (For Events)

    The parent component extends its access to child component methods and properties through this feature.

    Example

    @Injectable({ providedIn: 'root' })export class SharedService {private messageSubject = new Subject<string>();message$ = this.messageSubject.asObservable();sendMessage(message: string) {this.messageSubject.next(message);}}

    Sender Component:

    this.sharedService.sendMessage("Hello from Sender");

    Receiver Component:

    this.sharedService.message$.subscribe(message => console.log("Received:", message));

    Using Local Storage (Persist Data Across Components & Reloads)

    localStorage.setItem("sharedData", "Hello");console.log(localStorage.getItem("sharedData"));

    Using Angular Router (queryParams or state)

    Query Params:

    this.router.navigate(['/receiver'], { queryParams: { data: "Hello" } });this.route.queryParams.subscribe(params => console.log(params['data']));

    Using ViewChild() (Access Child Component from Parent)

    The parent component extends its access to child component methods and properties through this feature.

    Example

    Parent Component:

    @ViewChild(ChildComponent) child!: ChildComponent;ngAfterViewInit() {console.log(this.child.childMethod());}

    Child Component:

    childMethod() {return "Data from Child";}

    Using ViewChildren() (Access Multiple Child Components)

    Like ViewChild(), but for multiple child components.

    Example

    @ViewChildren(ChildComponent) children!: QueryList<ChildComponent>;ngAfterViewInit() {this.children.forEach(child => console.log(child.childMethod()));}

    Using ContentChild() (Project Content into a Component)

    Useful when using <ng-content>.

    Example

    Parent Template:

    <app-child><p #contentRef>Projected Content</p></app-child>

    Child Component:

    @ContentChild('contentRef') content!: ElementRef;ngAfterContentInit() {console.log(this.content.nativeElement.innerText);}

    Using ngModel (Two-Way Data Binding)

    For sharing data between a form control and a component.

    Example

    <input [(ngModel)]="sharedData">

    Using a Global Variable (Not Recommended)

    A simple but not recommended method.

    export let sharedData = "Global Data";

    Access it anywhere:

    import { sharedData } from './global';console.log(sharedData);

    Conclusion

    Angular provides multiple ways to share data between components, each suitable for different scenarios. Choose the method that best fits your application's architecture and requirements to ensure efficient and maintainable code.

    Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Angular Expertise.

    Contact Us

    Comment

    Share

    facebook
    LinkedIn
    Twitter
    Mail
    Angular

    Related Center Of Excellence