Home >Web Front-end >JS Tutorial >How can sibling components communicate in Angular 2?

How can sibling components communicate in Angular 2?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-30 04:51:10281browse

How can sibling components communicate in Angular 2?

Angular 2 Component Communication Amongst Siblings

In Angular 2, sibling component communication can be achieved through dependency injection and shared services.

Shared Service Approach (Angular 2 RC4 and Later)

The recommended approach involves creating a shared service that sibling components can access via dependency injection. Here's an example:

// shared.service.ts
@Injectable()
export class SharedService {
  dataArray: string[] = [];

  insertData(data: string) {
    this.dataArray.unshift(data);
  }
}

Parent Component:

// parent.component.ts
@Component({
  providers: [SharedService],
  directives: [ChildComponent, ChildSiblingComponent]
})
export class parentComponent { }

Sibling Components:

// child.component.ts
constructor(private _sharedService: SharedService) { }
ngOnInit(): void {
  this.data = this._sharedService.dataArray;
}

// child-sibling.component.ts
constructor(private _sharedService: SharedService) {}
addData() {
  this._sharedService.insertData(this.data);
  this.data = '';
}

Benefits of this Method:

  • Simple to implement
  • Supports direct communication between sibling components without the need for an event emitter or $rootScope.$broadcast
  • Allows for sharing of data between multiple components

Note:

  • Provide the service in the parent component only, but import it in both child components.

The above is the detailed content of How can sibling components communicate in Angular 2?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn