Angular 2 Sibling Component Communication

前端 未结 12 1290
深忆病人
深忆病人 2020-11-22 06:31

I have a ListComponent. When an item is clicked in ListComponent, the details of that item should be shown in DetailComponent. Both are on the screen at the same time, so

12条回答
  •  盖世英雄少女心
    2020-11-22 07:07

    Updated to rc.4: When trying to get data passed between sibling components in angular 2, The simplest way right now (angular.rc.4) is to take advantage of angular2's hierarchal dependency injection and create a shared service.

    Here would be the service:

    import {Injectable} from '@angular/core';
    
    @Injectable()
    export class SharedService {
        dataArray: string[] = [];
    
        insertData(data: string){
            this.dataArray.unshift(data);
        }
    }
    

    Now, here would be the PARENT component

    import {Component} from '@angular/core';
    import {SharedService} from './shared.service';
    import {ChildComponent} from './child.component';
    import {ChildSiblingComponent} from './child-sibling.component';
    @Component({
        selector: 'parent-component',
        template: `
            

    Parent

    `, providers: [SharedService], directives: [ChildComponent, ChildSiblingComponent] }) export class parentComponent{ }

    and its two children

    child 1

    import {Component, OnInit} from '@angular/core';
    import {SharedService} from './shared.service'
    
    @Component({
        selector: 'child-component',
        template: `
            

    I am a child

    • {{data}}
    ` }) export class ChildComponent implements OnInit{ data: string[] = []; constructor( private _sharedService: SharedService) { } ngOnInit():any { this.data = this._sharedService.dataArray; } }

    child 2 (It's sibling)

    import {Component} from 'angular2/core';
    import {SharedService} from './shared.service'
    
    @Component({
        selector: 'child-sibling-component',
        template: `
            

    I am a child

    ` }) export class ChildSiblingComponent{ data: string = 'Testing data'; constructor( private _sharedService: SharedService){} addData(){ this._sharedService.insertData(this.data); this.data = ''; } }

    NOW: Things to take note of when using this method.

    1. Only include the service provider for the shared service in the PARENT component and NOT the children.
    2. You still have to include constructors and import the service in the children
    3. This answer was originally answered for an early angular 2 beta version. All that has changed though are the import statements, so that is all you need to update if you used the original version by chance.

提交回复
热议问题