将项目添加到 angular material table

Adding items to angular material table

你好,我想将对象推送到数组元素数据并显示在 table 中,但是当我这样做时没有任何反应,我的 table 是空的。我是新手,我正在学习,我在哪里犯了错误?

我有应用程序组件和一个对话框组件,当我将信息插入对话框时,在按钮添加时,在关闭对话框时,我发送该数据并推入数据元素数组。

应用组件:

    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);
      });
      }
    }

对话框组件:

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);
  }
}

只需在 table 中添加一个引用变量(是的,#table)

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

在您的 app.component

中添加 viewChild
import {MatTable} from '@angular/material/table' //<--you need import MatTable

@ViewChild('table', { static: true,read:MatTable }) table

在你的函数中打开对话框

 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
      });
  }