0
votes

Angular 2, problem in updating md-table child component

So I have 3 components: Parent component containing component1 and component2, example:

<html of parent component>    
    <component1> </ component1>    
    <component2> </ component2> 
</ html parent>

The component2 has a list of items that appear in a table, there is an action that is performed on component1 that needs to add items to the list of component2 and then needs to update it. I did the following, in component1 constructor I injected component2:

Example in constructor of component1:

constructor (private component2: Component2) {}

. . This way I can use all the methods of component1 and even add all the items in the list of component1, so far so good, the items are added, the problem is that after adding the items to the list the table does not update these new items, and I I know the items are there because if I try to add new items in componet1 it warns that it is already there, it just did not update the table. . . The following is an example of how this part was implemented:

///////////////////// COMPONENT2 with the table:

let dataBase: Items [] = [];
export class COMPONENT1 implements OnInit, OnChanges {

public dataSource: ExampleDataSource;

ngOnChanges (changes: SimpleChanges) {
  dataBase = this.listWithItems;
  this.createDataSource ();
}

private createDataSource () {
  this.dataSource = new ExampleDataSource (dataBase);
}

// This method is used by component1 to update the table
public updateListListList () {
  dataBase = this.listWithItens
  this.createDataSource ();
}

COMPONENT2 HTML

<md-table #table [dataSource] = "dataSource" mdSort>
 ...
 ...
</ md-table>

COMPONENT1

 constructor (private component2: Component2) {}

. . Method using component1:

methodUpdatingListChild() {
  this.component2.listWithItens = "At this point I add all the items I want to 
  add to the table of component2"
  this.component1.updateLocalListList ();
}

. . In this call as I said, I can add the items in the list, they are there because I can not add repeated items to the list, and after this action if I try to add something it warns that the item is already in the list, I just need to update the component1 table being in component2, any solution?

2

2 Answers

0
votes

Better way to do this would be to leverage a service with Subject/Observables.

To communicate between two components that are not hierarchically nested it is still the best way.

Documentation with example : Components communication via service

0
votes

I was using the md-table of the material, tried several solutions and none of them made this tilt work, so I changed the md-table for a simple table and it worked, Herezia thanks for the help, I did not know the Observer, component that the solution I showed above step and everything was ok.