angular таблица материалов l oop через массив элементов - PullRequest
0 голосов
/ 31 января 2020

Я пытаюсь напечатать в Mat-table мои данные.

Я очень близок, но не могу завершить мой интерфейс.

Мои данные:

0: {Group: 1, Rules: Array(1), Title: "NAME"}
1: {Group: 2, Rules: Array(2), Title: "TERRITORY"}

And the array for Group 1 have rules like this (and so on for Group 2):
0: {Date: "1990-01-01", NewRules: 0, Rules: "Ligue Name", Id: 1}
1: {Date: "1990-01-01", NewRules: 1, Rules: "Other rules", Id: 2}

вот код. html:

<mat-card-content>
  <table mat-table [dataSource]="rules$ | async" class="mat-elevation-z8">

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

    <!-- Reglement Column -->
    <ng-container matColumnDef="Rules">
      <th mat-header-cell *matHeaderCellDef>Rule</th>
      <td mat-cell *matCellDef="let element">
        {{ element.Rules[0].Rules }}
      </td>
    </ng-container>

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

Что у меня получится, все нормально, если я укажу: element.Rules [0] .Rules

Но я хочу l oop через каждый элемент массива.

Предоставление чего-либо

Date       Rules

1990/1/1  Ligue Name

1990/1/1  Other Rules

Также, если вы можете дать мне эту подсказку тоже. Как я могу напечатать для каждой группы заголовок перед всеми правилами?

Group : NAME

Date       Rules

1990/1/1  Ligue Name

1990/1/1  Other Rules

Group: TERRITORY
 etc....

file .ts:

import { Component, OnInit, Input } from "@angular/core";
import { Reglements } from "../models/models";
import { MatDialog } from "@angular/material";
import { FirebaseService } from "../service/firebase.service";
import { Observable } from "rxjs";

@Component({
  selector: "app-reglements",
  templateUrl: "./reglements.component.html",
  styleUrls: ["./reglements.component.css"]
})
export class ReglementsComponent implements OnInit {
  displayedColumns: string[] = ["Date", "Rules"];

  @Input()
  // public boardDirection: AngularFireList<Direction[]>;
  public reglements$: Observable<Reglements[]>;

  constructor(
    private dialog: MatDialog,
    private firebaseService: FirebaseService
  ) {
    this.reglements$ = firebaseService.loadAllRules();
    this.reglements$.forEach(element => {
      console.log("eleem", element);
    });
  }

  ngOnInit() {}
}

Спасибо

Ответы [ 2 ]

2 голосов
/ 01 февраля 2020

Если вы хотите провести l oop через каждое правило в данных, вы можете использовать вложенную таблицу. Я создал код для вложенной таблицы, используя angular материал нажмите здесь

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

Что я понял в вашем вопросе, так это то, что у вас есть словарь группы, правил и названия. Среди них rules - это массив словарей, и вы хотите, чтобы l oop прошел через этот словарь и распечатал его в виде таблицы. Итак, вот как выглядит ваш источник данных:

dataSource = [
               {group: 1, rules: [{'date': '2019-1-31', 'rules': 'Some Rule', id: 1}, {'date': '2019-1-27', 'rules': 'Some Rule', id: 2}], title: 'name'},
               {group: 2, rules: [{'date': '2019-1-31', 'rules': 'Some Rule', id: 1}, {'date': '2019-1-27', 'rules': 'Some Rule', id: 2}], title: 'TERRITORY'}
             ]

После изменения кода:

 <table mat-table [dataSource]="dataSource">
     <ng-container matColumnDef="yourColName">
       <th mat-header-cell *matHeaderCellDef>Group</th>
       <td mat-cell *matCellDef="let element">
           {{element.group}}
       </td>
     </ng-container>
     <ng-container matColumnDef="yourColName">
       <th mat-header-cell *matHeaderCellDef>Rules Array Object</th>
       <td mat-cell *matCellDef="let element">
          <!--THIS IS WHERE YOU ARE ITERATING THROUGH ARRAY OF RULES OBJECT-->
           <ng-container *ngFor="let rule of element.rules">
               {{ rule.date}}, {{rule.rules}}, {{rule.id}}
           </ng-container>
       </td>
     </ng-container>
 </table>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...