我想将我的表单数据推送到列表中并将其显示在 mat-table 中(使用 angular 12)

I want to push my form data inside a list and show it in mat-table in (using angular 12)

我想将我的反应 form-data 值推送到列表中并在 mat-table 中显示。 目前,我的 mat-table 数据源采用这种格式。

Array(1) 0:{ brand: "" color: "" description: "" image: "" item_name: "asd" manufacturer: "" other: "" storage: "" tax: "" type: "Goods" unit: "pc"}

front-end 没有渲染,仅显示 table 中的 header

Ts 文件:

itemEntryForm:FormGroup;
  imagePreview:string;
  dataSource=[]
  displayedColumns: string[] = ['type', 'name', 'description', 'unit'];
ngOnInit(): void {
    this.itemEntryForm=this._formbuilder.group({
      type           :     ['Goods'], 
      item_name      :     ['',Validators.required],
      description    :     ['',Validators.required],
      unit           :     ['pc',Validators.required],  })
  }
 addItem(){
  this.dataSource.push(this.itemEntryForm.value)
  // this.dataSource=this.itemEntryForm.value
  console.log(this.dataSource)

  }

HTML:

<table mat-table [dataSource]="dataSource" *ngIf="dataSource" class="mat-elevation-z8 mx-auto">..

改为这样写:

  addItem(){
     this.dataSource = [...this.dataSource, this.itemEntryForm.value]
  }

这将为列表创建一个新的引用,允许 mat-table 接受更改。或者,您可以注入 ChangeDetectorRef 和 运行 .detectChanges() - 这也可以解决问题。