代码之家  ›  专栏  ›  技术社区  ›  Tare

为什么没有数据源的<mat table>不显示在Angular 7中

  •  0
  • Tare  · 技术社区  · 5 年前

    我想用 <mat-table> 显示选项的名称及其对应的给定值(供用户更改)。由于选项可能需要通过不同的方式(例如滑动切换或mat选择)设置它们的值,因此我必须在没有数据源的情况下将其记录下来(或者至少据我所知,不能在typescript文件中使用预先编写的html标记)。

    因此,我的MWE是:

    <mat-table>
        <mat-header-row *matHeaderRowDef>
            <mat-header-cell>header</mat-header-cell>
        </mat-header-row>
    
        <mat-row>
            <mat-cell>
                 cell
            </mat-cell>
        </mat-row>
    </mat-table>
    

    然而,当我查看页面时,它只显示一行,没有任何字符串。我想在一小时内使用这张桌子 <mat-card> (或者更确切地说 <mat-card-content> ),但即使我在那之外尝试,我也只得到了那条线,别的什么都没有。这是mat卡中的外观:

    Blank Line

    如何正确显示表格?


    *编辑:* 既然它是被要求的,这里也是答案。ts文件。

    import { Component, OnInit, ViewChild } from '@angular/core';
    
    @Component({
      selector: 'app-general',
      templateUrl: './general.component.html',
      styleUrls: ['./general.component.scss']
    })
    export class GeneralComponent implements OnInit {
    
    
      @ViewChild('resolutionSelect') resolutionSelect: MatSelect;
    
      resolutions: ResolutionOptionsInterface[] = [
        { value: '1920 x 1080' },
        { value: '800 x 600' }
      ];
      public selectedRes = this.resolutions[0];
      public isFullscreenEnabled = true;
    
      constructor() { }
    
      ngOnInit() {
        console.log("in oninit");
        this.resolutionSelect.value = this.resolutions[0].value;
      }
    
    }
    

    这比最简单的工作示例多一点,所以我将解释一下:

    • 我的选择之一是分辨率,它可以由 mat-select
    • 垫子选择 在html文件中定义如下
    • 垫子选择 将给定预定义的值,如 resolutions 大堆
    • 我的另一个选择就是选择全屏,让它成为一个 mat-slide-toggle (然而,这一点尚未完全实施)

      <mat-select #resolutionSelect fxFlex="200px"> <mat-option *ngFor="let res of resolutions" [value]="res.value" class="right"> {{res.value}} </mat-option> </mat-select>

    0 回复  |  直到 5 年前
        1
  •  20
  •   talhature    5 年前

    事实上,可以在没有数据源的情况下创建材质表。 您需要确保使用显示的列和所有列创建了标题定义。

    示例-html文件:

    <table mat-table class="mat-elevation-z8">
      <ng-container matColumnDef="someValue">
        <th mat-header-cell *matHeaderCellDef mat-sort-header>Some Value Header</th>
      </ng-container>
    
      <ng-container matColumnDef="someOtherValue">
        <th mat-header-cell *matHeaderCellDef mat-sort-header>
          Some Other Value Header
        </th>
      </ng-container>
    
      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
    </table>
    

    在ts文件中,需要定义数组

    displayedColumns: string[] = ['someValue', 'someOtherValue'];
    

    编辑: 如果您的需求只是一个带有几个预定义值的简单表格,那么您可以通过使用带有材质css类的本机表格元素来实现:

    <table class="mat-table" >
      <tr class="mat-header-row">
        <th class="mat-header-cell">A</th>
        <th class="mat-header-cell">B</th>
      </tr>
      <tr class="mat-row">
        <td class="mat-cell">A</td>
        <td class="mat-cell">B</td>
      </tr>
    </table>
    
    推荐文章