使用MatTableDataSource和ViewChild来动态计算表格高度并设置max-height属性。以下是代码示例:
HTML:
  ...
 
TypeScript:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
@Component({
  selector: 'app-table-example',
  templateUrl: './table-example.component.html',
  styleUrls: ['./table-example.component.scss']
})
export class TableExampleComponent implements OnInit {
  @ViewChild('table') table: ElementRef;
  dataSource = new MatTableDataSource();
  tableHeight: string;
  ngOnInit(): void {
    this.dataSource.data = [{...}, {...}, ...];
    this.calculateTableHeight();
  }
  calculateTableHeight() {
    const tableElement = this.table.nativeElement;
    const headerEnd = tableElement.querySelector('.mat-header-row').getBoundingClientRect().bottom;
    const footerStart = tableElement.querySelector('.mat-footer-row').getBoundingClientRect().top;
    const height = footerStart - headerEnd;
    this.tableHeight = `${height}px`;
  }
}
在ngOnInit中设置数据源并调用calculateTableHeight来计算表格高度。calculateTableHeight中使用ElementRef和querySelector获取表格头和表格尾的坐标,并计算表格高度。最后将表格高度设置为max-height属性的值。