Sharing data between Angular components

Problem

As a result of working with the Angular framework, we decompose our web application. And therefore, we have a situation when we need to transfer data between components.





@Input ()

To pass data to a child component, we can use a decorator @Input()



. It will allow us to pass data from the parent component to the child component. Let's look at a simple example:





import { Input, Component} from '@angular/core';
      
@Component({
    selector: 'app-child',
    template: `<h1>Title: {{ title }}</h1>`
})
export class ChildComponent { 
    @Input() title: string;
}
      
      



In the child component, we have "decorated" the property we need title



. Don't forget to import the decorator:





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



It remains only to pass the parameter title



to the child component from the parent:





import { Component } from '@angular/core';
      
@Component({
    selector: 'app-component',
    template: `<app-child [title]="title" [userAge]="age"></app-child>`
})
export class AppComponent { 
    public title = 'Hello world!';
}
      
      



[title]="title"



, title="Hello world"



. , ?





@Output()

@Output()



. , :





import { Component } from '@angular/core';
       
@Component({
    selector: 'app-counter',
    template: `<h1>Count: {{ count }}</h1>
              <app-add (buttonClick)="onAdd()"></app-add>`
})
export class AppCounter { 
    public count = 0;

public onAdd(): void {
    this.count++;
}

}
      
      



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

@Component({
    selector: 'app-add',
    template: `<button (click)="add()"></button>`;
})
export class AppAdd { 
    @Output() buttonClick = new EventEmitter();

		public add(): void {
    	this.buttonClick.emit();
		}
}
      
      



. AppAdd



click



, add()



. this.buttonClick.emit() buttonClick



AppCounter



. EventEmitter



:





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



"", . :





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

@Component({
    selector: 'app-better-counter',
    template: `<h1>Count: {{ count }}</h1>
							<app-buttons (buttonClick)="onChange($event)"></app-buttons>`
})
export class BetterCounterComponent { 
    public count = 0;

		public onChange(isAdd: boolean): void {
      if (isAdd) {
        this.count++;
      } else {
          this.count--;
      }
	 }
}
      
      



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

@Component({
    selector: 'app-buttons',
    template: `<button (click)="change(true)"></button>                
							 <button (click)="change(false)"></button>`
})
export class ButtonsComponent { 
    @Output() buttonClick = new EventEmitter<boolean>();

		public change(change: boolean): void {
    	this.buttonClick.emit(change);
		}
}
      
      



:





  • new EventEmitter<



    boolean>()







  • emit



    this.buttonClick.emit(change)







  • $event



    (buttonClick)="onChange($event)"







@Input()



@Output()



, , , .., .





RxJs

. , :





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

@Injectable({
  providedIn: 'root',
})
export class SimpleService {
    public count$ = new Subject<number>();

		public changeCount(count: number) {
   		this.count$.next(count); 
  	}
}
      
      



. count$



. - . Subject



. Subject



- , . , Subject



. , count



:






import { SimpleService } from './services/simple.service.ts';

@Component({
    selector: 'app-any',
    template: ``
})
export class AnyComponentComponent { 
    constructor(
          private readonly simpleService: SimpleService
    ) {}
  
  	public setAnyCount(): void {
      this.simpleService.changeCount(Math.random());
		}
}
      
      



Math.random()



. :





import { Component, OnInit } from '@angular/core';
import { SimpleService } from './services/simple.service.ts';

@Component({
    selector: 'app-other',
    template: ``
})
export class OtherComponentComponent implements OnInit { 
    constructor(
       private readonly simpleService: SimpleService
    ) {}
  
    ngOnInit(): void {
      this.simpleService.count$.subscribe((count) => this.log(count));
    }

    private log(data: number): void {
  		console.log(data);
    }

}
      
      



count



, count$.next(...)



- subscribe



. - . , , . , . log()



, . - , . , count$



OnDestroy



. unsubscribe()



:





import { Component, OnInit, OnDestroy } from '@angular/core';
import { SimpleService } from './services/simple.service.ts';
import { Subsription } from 'rxjs';

@Component({
    selector: 'app-other',
    template: ``
})
export class OtherComponentComponent implements OnInit, OnDestroy {
   	private subs: Subsription;

    constructor(
      private readonly simpleService: SimpleService
    ) {}

    ngOnInit(): void {
      this.subs = this.simpleService.count$.subscribe((count) => this.log(count));
    }

    ngOnDestroy(): void {
  		this.subs.unsubscribe();
		}

    private log(data: number): void {
  		console.log(data);
    }
}
      
      



We can subscribe to many Subjects from a component, subscribe to the same Subject from different components.





Outcome

We can share data between components using @Input()



, @Output()



and RxJs. In this article, I omitted store



, since the article is intended for beginners. I advise you to practice this topic to improve your skills.








All Articles