0

I have a Material Data table, which the user can fill and empty by himself. The data, which gets into the table gets triggered by a service, which I initialized in the table component with ngOnInit().

Code:

  ngOnInit() {
    this._AS.transaction$.subscribe( transaction => {
        this.transaction = transaction;
        this.temp = this.dataSource.data.slice();
        this.temp.push(this.transaction); // Stop this call on init somehow?
        this.dataSource.data = this.temp;
        this.ref.detectChanges();
        console.log(this.transaction);
      }
    );
  }

The problem is: There is always an empty row which gets pushed by the call this.temp.push(this.transaction). Is there a way to stop this call for the first time or something similar?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Michael
  • 287
  • 1
  • 10
  • 17

2 Answers2

0

Why is it empty, because 'transaction' is? So why don't you just use an if query? Or you could declare a (bool) variable in your parent component and set it on true the first time you hit ngOnInit

constructor( public parentComponent: ParentComponent) {

}

ngOnInit() {
  if(parent.isInitialized) {
    this._AS.transaction$.subscribe( transaction => {
      this.transaction = transaction;
      this.temp = this.dataSource.data.slice();

      if(parent.isInitialized) {
        this.temp.push(this.transaction); // Stop this call on init somehow?
      } else {
        parent.isInitialized = true;
      }

      this.dataSource.data = this.temp;
      this.ref.detectChanges();
      console.log(this.transaction);
    } );
}
guwluws
  • 211
  • 1
  • 3
  • 13
  • I just tried that. It didn't work. The empty row is gone and the bool is set to true. But if I want to add data to the table it doesn't display that data. – Michael Dec 19 '18 at 14:58
  • Oh okay, what if you do the if(parent.isInitialized in the subscribe closure? See edit – guwluws Dec 19 '18 at 15:29
0

I just used an alternative way: After pushing the empty Transaction into the table I pop it afterwards, so that the table is empty again. Pushing data works now without problems.

  ngOnInit() {
      this._AS.transaction$.subscribe(transaction => {
          this.transaction = transaction;
          this.temp = this.dataSource.data.slice();
          this.temp.push(this.transaction);
          this.dataSource.data = this.temp;
          this.ref.detectChanges();
        }
      );
      this.temp = this.dataSource.data.slice();
      this.temp.pop();
      this.dataSource.data = this.temp;
      this.ref.detectChanges();
  }
Michael
  • 287
  • 1
  • 10
  • 17