Отображение таблицы материалов в Angular - PullRequest
0 голосов
/ 04 февраля 2020

Я довольно новичок в Angular и пытаюсь создать таблицу, чтобы лучше отображать мои данные. Я получаю данные от JSON, предоставленного моим сервером.

Содержимое data.component.html:

<div class="container">
  <h1>Search history</h1>
  <table *ngIf="searches">
    <li *ngFor="let search of searches">
      <p class="searchParams">{{search.searchParams}}</p>
      <p class="searchDate">{{search.searchDate | date: "yyyy-MM-dd hh:mm"}}</p>
    </li>
  </table>
</div>

Содержимое data.component.ts:

@Component({
  selector: 'app-data',
  templateUrl: './data.component.html',
  styleUrls: ['./data.component.scss']
})
export class DataComponent implements OnInit {
  searches: Object;
  constructor(private _http: HttpService) {
  }

  ngOnInit() {
    this._http.getSearches().subscribe(data => {
      this.searches = data;
      console.log(this.searches);
    });
  }
}

То, что я получаю, выглядит как список маркеров:

enter image description here

Я пытаюсь взять этот в качестве примера но я не понимаю, как это реализовать. Каков мой источник данных здесь? Что HTML я должен написать, чтобы получить такой красивый стол?

Ответы [ 2 ]

1 голос
/ 04 февраля 2020

Примерно так может работать,

data.component.html

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

  <!-- Position Column -->
  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef> No. </th>
    <td mat-cell *matCellDef="let element"> {{element.position}} </td>
  </ng-container>

  <!-- Keyword Column -->
  <ng-container matColumnDef="keyword">
    <th mat-header-cell *matHeaderCellDef> Keyword </th>
    <td mat-cell *matCellDef="let element"> {{element.keyword}} </td>
  </ng-container>

  <!-- Limit Column -->
  <ng-container matColumnDef="limit">
    <th mat-header-cell *matHeaderCellDef> Limit </th>
    <td mat-cell *matCellDef="let element"> {{element.limit}} </td>
  </ng-container>

  <!-- Date Search Column -->
  <ng-container matColumnDef="dateSearch">
    <th mat-header-cell *matHeaderCellDef> Date Search </th>
    <td mat-cell *matCellDef="let element"> {{element.dateSearch | date: "yyyy-MM-dd hh:mm"}} </td>
  </ng-container>

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

data.component.ts

@Component({
  selector: 'app-data',
  templateUrl: './data.component.html',
  styleUrls: ['./data.component.scss']
})
export class DataComponent implements OnInit {
  searches: Object;
  displayedColumns: string[] = ['position', 'keyword', 'limit', 'date'];
  dataSource = ELEMENT_DATA;
  constructor(private _http: HttpService) {
  }

  ngOnInit() {
    this._http.getSearches().subscribe(data => {
      this.searches = data;
      this.dataSource = data.map((v, i) => {
        position: i,
        keyword: v.searchParams.keyword,
        limit: v.searchParams.limit,
        dateSearch: v.searchDate
      });
      console.log(this.searches);
    });
  }
}
1 голос
/ 04 февраля 2020

Если вы хотите что-то вроде таблицы материалов angular, вы должны использовать ее и следовать документам.
Если вы не хотите использовать материал angular, а просто хотите обычную таблицу HTML, Вы должны настроить свой код так, чтобы он использовал строки и столбцы таблицы Actale:

<div class="container">
  <h1>Search history</h1>
  <table *ngIf="searches">
    <tr *ngFor="let search of searches">
      <td class="searchParams">{{search.searchParams}}</p>
      <td class="searchDate">{{search.searchDate | date: "yyyy-MM-dd hh:mm"}}</p>
    </tr>
  </table>
</div>

Затем вы можете оформить таблицу с помощью CSS.

. Для подхода angular материала вы должны сначала установите пакет и импортируйте его в свой модуль. Тогда вы можете использовать такой шаблон:

<table mat-table [dataSource]="searches" class="mat-elevation-z8">    
  <!-- searchParams Column -->
  <ng-container matColumnDef="searchParams">
    <th mat-header-cell *matHeaderCellDef> Search parameters </th>
    <td mat-cell *matCellDef="let element"> {{element.searchParams}} </td>
  </ng-container>

  <!-- searchDate Column -->
  <ng-container matColumnDef="searchDate">
    <th mat-header-cell *matHeaderCellDef> Date </th>
    <td mat-cell *matCellDef="let element"> {{element.searchDate}} </td>
  </ng-container>

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

Не забудьте определить displayColumns в коде:

displayedColumns: string[] = ['searchParams', 'searchDate'];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...