Search code examples
arraysangularlistpushmaterial-table

Adding items to angular material table


Helloo, i want to push object to array element data and to show in table, but when i do it nothing happend, my table is empty. I am new to this and i am learning, where i made a mistake?

I have app component and one more dialog component, when i insert information into dialog, on button add, on close dialog, i send that data and push into data element array.

App component:

    export interface PeriodicElement {
      videoname: string;
      url: string;
      author: string;
      description: string;
    }

    const ELEMENT_DATA: PeriodicElement[] = [];

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })

    export class AppComponent {
      title = 'Zadatak';

      displayedColumns: string[] = ['videoname', 'author', 'description', 'url' ];
      dataSource = ELEMENT_DATA;

      constructor(public dialog: MatDialog, private changeDetectorRefs: ChangeDetectorRef) {}


      openDialog(): void {
      const dialogRef = this.dialog.open(AddVideoFormComponent);
      dialogRef.afterClosed().subscribe(data => {
      ELEMENT_DATA.push(data);
      });
      }
    }

Dialog component:

export class AddVideoFormComponent implements OnInit {
  videoForm: FormGroup;

  constructor(public dialogRef: MatDialogRef<AddVideoFormComponent>) { }

  ngOnInit() {
    this.videoForm = new FormGroup({
      videoname : new FormControl('', Validators.required),
      url : new FormControl('', Validators.required),
      author : new FormControl('', Validators.required),
      description : new FormControl('', Validators.required),
    });
  }

  onSubmit() {
    this.dialogRef.close(this.videoForm.value);
  }
}

Solution

  • just add a reference variable in your table (yes, the #table)

    <table #table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
      ...
    </table>
    

    Add viewChild in your app.component

    import {MatTable} from '@angular/material/table' //<--you need import MatTable
    
    @ViewChild('table', { static: true,read:MatTable }) table
    

    In your funcion openDialog

     openDialog(): void {
          const dialogRef = this.dialog.open(AddVideoFormComponent);
          dialogRef.afterClosed().subscribe(data => {
            this.dataSource.push(data); //<--make the push on dataSource
            this.table.renderRows()  //<--say to Angular that render the rows
          });
      }