Skip to content Skip to sidebar Skip to footer

Update The Data In One Component Based On What Is Clicked In Another Component In Angular 2

I have two components let's call them CompA and CompB. I would like for the clicked item object in CompA to appear in CompB. Here is what I have done so far. CompA: import {Compo

Solution 1:

Thats because the Component B you got injected in the constructor is not the component B used in the application. Its another component B that the hierarchical injector created, when Component B was added to the list of providers.

One way to do it is to create a separate injectable service, and inject it in both components. One component subscribes to the service and the other triggers a modification. For example:

@Injectable()
exportclassItemsService {

    private items = newSubject(); 

    newItem(item) {
        this.subject.next(item);
    }
}

This needs to be configured in the bootstrap of the Angular 2 app:

boostrap(YourRootComponent, [ItemsService, ... other injectables]);

And then inject it on both components. Component A sends new items:

exportclassCompA {
    constructor(private itemsService: ItemsService){}

    show(item){
        this.itemsService.newItem(item);
    }
}

And component B subscribes to new items:

exportclassCompB {
    constructor(itemsService: ItemsService){
        itemsService.items.subscribe((newItem) => {
            //receive new item here
        });
    }

Have a look at the async pipe, as its useful to consume observables in the template directly.

Solution 2:

If you get a CompB instance passed to

constructor(public _compB: CompB){}

it's not the instance you expect but a different (new) one.

There are different strategies to communicate between components. This depends on how they are related in the view. Are they siblings, parent and child or something else. Your question doesn't provide this information.

For parent and child you can use data binding with inputs and outputs.

For siblings you can use data binding if you include the common parent (use it as mediator)

You always can use a shared service.

For data-binding details see https://angular.io/docs/ts/latest/guide/template-syntax.html

Post a Comment for "Update The Data In One Component Based On What Is Clicked In Another Component In Angular 2"