向角形材料表添加项目

时间:2020-03-24 14:11:55

标签: arrays angular list push material-table

Helloo,我想将对象推送到数组元素数据并在表中显示,但是当我什么都没做时,我的表是空的。我对此很陌生,正在学习,我在哪里犯了错误?

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

应用程序组件:

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

1 个答案:

答案 0 :(得分:0)

只需在表中添加一个引用变量(是,#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中

 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
      });
  }
相关问题