Angular 2 Sibling Component Communication

前端 未结 12 1488
深忆病人
深忆病人 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:21

    Shared service is a good solution for this issue. If you want to store some activity information too, you can add Shared Service to your main modules (app.module) provider list.

    @NgModule({
        imports: [
            ...
        ],
        bootstrap: [
            AppComponent
        ],
        declarations: [
            AppComponent,
        ],
        providers: [
            SharedService,
            ...
        ]
    });
    

    Then you can directly provide it to your components,

    constructor(private sharedService: SharedService)
     
    

    With Shared Service you can either use functions or you can create a Subject to update multiple places at once.

    @Injectable()
    export class SharedService {
        public clickedItemInformation: Subject = new Subject(); 
    }
    

    In your list component you can publish clicked item information,

    this.sharedService.clikedItemInformation.next("something");
    

    and then you can fetch this information at your detail component:

    this.sharedService.clikedItemInformation.subscribe((information) => {
        // do something
    });
    

    Obviously, the data that list component shares can be anything. Hope this helps.

提交回复
热议问题