Home > Net >  Angular Material @ViewChield MatTable: How Update table?
Angular Material @ViewChield MatTable: How Update table?

Time:02-17

I have a child component that uses MatTable. I need update the table after edit or create using renderRows(); The table datasource is an @Input(). I have tried onChanges, but I got undefined because of @ViewChild.

Where Do I have to put renderRows() to update table when the products[] is updated? In this case, the table is updated, but with undefined message error.

Child Component:

  //Table datasource
  @Input()
  products: Product[] = [];


  @ViewChild(MatTable)
  table !: MatTable<Product>;

  ngOnChanges(){
    this.table.renderRows(); //works but I got undefined
  }


In the parent component, when the state changes:

   this.productService.saveProduct(product).subscribe({
          next: data => {
            this.products.push(data);
          }
    });

If I change to reload and create a new array, it works perfect, but I dont want to call my rest api:

 loadProducts() {
    this.productService.getProducts().subscribe({
      next: data => { this.products = data }
    });
  }
this.productService.saveProduct(product).subscribe({
          next: data => {
                this.loadProducts()        
          }
});

CodePudding user response:

I have a potencial solution.

Now I dont have undefined and the the works perfect, but repeat twice the same line looks wrong for me.

  ngAfterViewInit() {
    this.dataSource =  new MatTableDataSource(this.products);;
    this.table.renderRows();
  }

  ngOnChanges(){
    this.dataSource = new MatTableDataSource(this.products);
  }

CodePudding user response:

Simply check that the table is defined before calling the function

@ViewChild(MatTable)
  table?: MatTable<Product>;

  ngOnChanges(){
    if (table) this.table.renderRows(); //works but I got undefined
  }

! means that the variable is always defined, which in this case is not true. Use ? in these situations and the compiler will help you avoid these types of bugs.

  • Related