Home >Web Front-end >JS Tutorial >How Can I Communicate Between Sibling Components in Angular 2?

How Can I Communicate Between Sibling Components in Angular 2?

Linda Hamilton
Linda HamiltonOriginal
2024-11-14 13:40:02361browse

How Can I Communicate Between Sibling Components in Angular 2?

Angular 2 Sibling Component Communication

Sibling components do not have access to each other's properties and methods. This article explores a straightforward mechanism for communication between sibling components in Angular 2, utilizing a shared service.

Shared Service Approach

1. Shared Service:

Create a shared service to act as a communication hub.

@Injectable()
export class SharedService {
    dataArray: string[] = [];

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

2. Parent Component:

Import and provide the shared service in the parent component.

import {SharedService} from './shared.service';
@Component({
    selector: 'parent-component',
    template: `<child-component></child-component>
               <child-sibling-component></child-sibling-component>`,
    providers: [SharedService]
})
export class ParentComponent { }

3. Child Components:

Inject the shared service into both sibling components:

Child Component 1:

import {SharedService} from './shared.service'
@Component({
    selector: 'child-component',
    template: `...`
})
export class ChildComponent implements OnInit {
    data: string[] = [];
    constructor(private _sharedService: SharedService) { }
}

Child Component 2 (Sibling):

import {SharedService} from './shared.service'
@Component({
    selector: 'child-sibling-component',
    template: `...`
})
export class ChildSiblingComponent {
    data: string = 'Testing data';
    constructor(private _sharedService: SharedService) { }
}

4. Data Sharing:

The sibling component can modify the shared service's data array, which will be reflected in the other sibling component.

addData() {
    this._sharedService.insertData(this.data);
    this.data = '';
}

Notes:

  • Include the shared service provider only in the parent component to avoid creating multiple instances.
  • Import and inject the service into the sibling components.
  • Update the import statements for Angular 2 versions higher than beta.

The above is the detailed content of How Can I Communicate Between Sibling Components 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