【问题标题】:Adding items to angular material table将项目添加到角度材料表
【发布时间】:2020-03-24 14:11:55
【问题描述】:

您好,我想将对象推送到数组元素数据并显示在表中,但是当我这样做时什么也没发生,我的表是空的。我是新手,我正在学习,我在哪里犯了错误?

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

应用组件:

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

【问题讨论】:

  • 你能分享一下stackblitz的例子吗?
  • 在这个例子中只有 1 个组件,我不明白如何将 add() 与其他组件中的按钮连接起来?谢谢。我这样做了,但仍然不起作用: openDialog(): void { const dialogRef = this.dialog.open(AddVideoFormComponent); dialogRef.afterClosed().subscribe(data => { this.dataSource.data.push(ELEMENT_DATA[this.index++]); this.table.renderRows(); }); }
  • 不,你的推送必须是this.dataSource.push(data);。在我的例如从数组中推送一个元素,您从对话框中填写的数据中添加一个元素

标签: arrays angular list push material-table


【解决方案1】:

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

【讨论】:

  • 你帮了我很多,如果我看到你,你喝啤酒!
  • 是的,相信它:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-10
  • 1970-01-01
  • 1970-01-01
  • 2020-06-10
  • 1970-01-01
  • 2016-03-16
相关资源
最近更新 更多