Berbagi data antar komponen Angular

Masalah

Sebagai hasil dari bekerja dengan kerangka kerja Angular, kami menguraikan aplikasi web kami. Dan oleh karena itu, kami memiliki situasi ketika kami perlu mentransfer data antar komponen.





@Memasukkan ()

Untuk meneruskan data ke komponen anak, kita bisa menggunakan dekorator @Input()



. Ini akan memungkinkan kita untuk meneruskan data dari komponen induk ke komponen anak. Mari kita lihat contoh sederhana:





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



Dalam komponen anak, kita telah "menghias" properti yang kita butuhkan title



. Jangan lupa untuk mengimpor dekorator:





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



Tetap hanya meneruskan parameter title



ke komponen anak dari induk:





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);
    }
}
      
      



Kita dapat berlangganan banyak Subjek dari sebuah komponen, berlangganan Subjek yang sama dari komponen yang berbeda.





Hasil

Kami dapat berbagi data antar komponen menggunakan @Input()



, @Output()



dan RxJs. Pada artikel ini, saya hilangkan store



, karena artikel tersebut ditujukan untuk pemula. Saya menyarankan Anda untuk mempraktikkan topik ini untuk meningkatkan keterampilan Anda.








All Articles