【问题标题】:Why is this Angular Material table not rendering?为什么这个 Angular Material 表没有渲染?
【发布时间】:2020-05-29 11:09:08
【问题描述】:

我正在使用 Angular 9 和 Angular Material 开发联系人应用程序。列表组件应在表格行中为每个联系人显示一些信息和图像。

在我的app.module.ts 中,我导入了MatTableModule 等。

app\services\contacts-list.service.ts 我有:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map } from 'rxjs/operators';

import { Contact } from '../models/Contact';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  })
}

@Injectable({
  providedIn: 'root'
})

export class ContactsListService {

  contactsUrl = 'https://randomuser.me/api/?&results=20&inc=name,location,email,cell,picture';

  constructor(private http:HttpClient) { }

  getContcts():Observable<Contact[]> {
    return this.http.get<Contact[]>(`${this.contactsUrl}`)
      .pipe(map(response => response['results']));
  }

  getOneContact():Observable<Contact[]> {
    return this.http.get<Contact[]>(`${this.contactsUrl}`)
      .pipe(map(response => response['results']));
  }

}

app\components\list\list.component.ts我有:

import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { from } from 'rxjs';
import { ContactsListService } from '../../services/contacts-list.service';
import { Contact } from '../../models/Contact';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
})

export class ListComponent implements OnInit {

  pageTitle = 'My Contacts';

  contactsList:Contact[];

  constructor(private ContactsListService:ContactsListService) { }

  contactsTableData: MatTableDataSource<any>;
  displayedColumns: string[] = ['fullName', 'photo', 'email', 'city', 'country'];

  ngOnInit(): void  {
    // Contact list
    this.ContactsListService.getContcts().subscribe(
      contactsList => { 
        this.contactsList = contactsList; console.log(contactsList);
        this.contactsTableData = new MatTableDataSource(contactsList);
      },
      error => { }
    );
  }
}

我上面组件的模板:

<div class="container">
    <h2 class="mat-display-1 page-title">{{pageTitle}}</h2>
    <div class="mat-elevation-z8">
        <mat-table [data-source]="contactsTableData">

            <ng-container matColumnDef="fullName">
                <mat-header-cell *matHeaderCellDef> Full Name </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.name.first}} {{element.name.last}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="photo">
                <mat-header-cell *matHeaderCellDef> Photo </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.picture.large}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="email">
                <mat-header-cell *matHeaderCellDef> Email address </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.email}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="city">
                <mat-header-cell *matHeaderCellDef> City </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.location.city}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="phone">
                <mat-header-cell *matHeaderCellDef> Phone </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.cell}} </mat-cell>
            </ng-container>

            <ng-container matColumnDef="country">
                <mat-header-cell *matHeaderCellDef> Country </mat-header-cell>
                <mat-cell *matCellDef="let element"> {{element.location.country}} </mat-cell>
            </ng-container>

            <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
            <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
        </mat-table>
    </div>
</div>

问题

我面临的问题是只显示表头(列名)而没有数据,evan 认为组件中的行 console.log(contactsList) 正确显示了联系人:

[
  {
     "name":{
        "title":"Mr",
        "first":"Mair",
        "last":"da Cunha"
     },
     "location":{
        "street":{
           "number":1198,
           "name":"Rua Belo Horizonte "
        },
        "city":"Cachoeiro de Itapemirim",
        "state":"Tocantins",
        "country":"Brazil",
        "postcode":36034,
        "coordinates":{
           "latitude":"-78.1101",
           "longitude":"-171.0313"
        },
        "timezone":{
           "offset":"+5:00",
           "description":"Ekaterinburg, Islamabad, Karachi, Tashkent"
        }
     },
     "email":"mair.dacunha@example.com",
     "cell":"(66) 5998-0008",
     "picture":{
        "large":"https://randomuser.me/api/portraits/men/88.jpg",
        "medium":"https://randomuser.me/api/portraits/med/men/88.jpg",
        "thumbnail":"https://randomuser.me/api/portraits/thumb/men/88.jpg"
     }
  }
]

缺少什么?

【问题讨论】:

  • docs 似乎使用&lt;tr mat-header-row ...&gt;&lt;/tr&gt; 而不是&lt;mat-header-row ...&gt;&lt;/mat-header-row&gt;? (编辑:忽略我猜,他们也使用th mat-header-cell,但你说你的标题代码确实有效)
  • 文档似乎也使用dataSource 而不是data-source。您可以尝试更改它。
  • @AkashBhardwaj 确实是这个问题。
  • 是的,我在看一个旧的(呃)教程。谢谢!

标签: javascript angular angular-material


【解决方案1】:

在模板上,mat-table 应使用[dataSource] 而不是[data-source]。这应该可以解决您的问题。

另外快速提示,您的响应不会返回 ContactAM 数组,而是返回一个具有名为 results 的属性的对象,而该属性又具有 ContactAM 数组的值。因此,在您的service 上,您执行HTTP GET call 并将其输入为ContactAM[],您实际上应该将其输入为{ results: ContactAM[] }

【讨论】:

    【解决方案2】:

    以下是解决问题的方法,以防其他人可以使用此信息:

    app\components\list\list.component.ts 文件中我有:

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { MatTableDataSource } from '@angular/material/table';
    import { MatPaginator } from '@angular/material/paginator';
    import { from } from 'rxjs';
    import { ContactsListService } from '../../services/contacts-list.service';
    import { Contact } from '../../models/Contact';
    
    @Component({
      selector: 'app-list',
      templateUrl: './list.component.html',
    })
    
    export class ListComponent implements OnInit {
    
      pageTitle = 'My Contacts';
    
      contactsList:Contact[];
    
      constructor(private ContactsListService:ContactsListService) { }
    
      contactsTableData: MatTableDataSource<any>;
      displayedColumns: string[] = ['fullName', 'photo', 'email', 'phone', 'city', 'country'];
    
      @ViewChild(MatPaginator) paginator: MatPaginator;
    
      ngOnInit(): void  {
        // Contact list
        this.ContactsListService.getContcts().subscribe(
          contactsList => { 
            this.contactsList = contactsList;
            this.contactsTableData = new MatTableDataSource(contactsList);
            this.contactsTableData.paginator = this.paginator;
          },
          error => { }
        );
      }
    }
    

    在组件的模板中我有:

    <div class="container">
        <div class="mat-elevation-z8">
            <table mat-table [dataSource]="contactsTableData" class="w-100">
                <ng-container matColumnDef="fullName">
                    <th mat-header-cell *matHeaderCellDef>Full Name</th>
                    <td mat-cell *matCellDef="let element">{{element.name.first}} {{element.name.last}}</td>
                </ng-container>
    
                <ng-container matColumnDef="photo">
                    <th mat-header-cell *matHeaderCellDef>Photo</th>
                    <td mat-cell *matCellDef="let element">
                        <img src="{{element.picture.large}}" alt="{{element.name.first}} {{element.name.last}}" class="thumbnail rounded-circle">
                    </td>
                </ng-container>
    
                <ng-container matColumnDef="email">
                    <th mat-header-cell *matHeaderCellDef>Email address</th>
                    <td mat-cell *matCellDef="let element">
                        <a href="mailto:{{element.email}}">{{element.email}}</a>
                    </td>
                </ng-container>
    
                <ng-container matColumnDef="phone">
                    <th mat-header-cell *matHeaderCellDef>Phone</th>
                    <td mat-cell *matCellDef="let element">
                        <a href="tel:{{element.phone}}">{{element.cell}}</a>
                    </td>
                </ng-container>
    
                <ng-container matColumnDef="city">
                    <th mat-header-cell *matHeaderCellDef>City</th>
                    <td mat-cell *matCellDef="let element">{{element.location.city}}</td>
                </ng-container>
    
                <ng-container matColumnDef="country">
                    <th mat-header-cell *matHeaderCellDef>Country</th>
                    <td mat-cell *matCellDef="let element">{{element.location.country}}</td>
                </ng-container>
    
                <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
                <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
            </table>
            <mat-paginator [pageSizeOptions]="[10, 20, 50]" [pageSize]="10" showFirstLastButtons></mat-paginator>
        </div>
    </div>
    

    我也有这种样式,用于图像:

    .rounded-circle {
        border-radius: 50%!important;
    }
    
    .thumbnail {
        padding: 2px;
        line-height: 1;
        background-color: #fff;
        border: 1px solid #ddd;
        height: 40px;
        width: auto;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-21
      • 2014-01-20
      • 2021-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多