ngIf в ng-контейнере внутри mat-таблицы - PullRequest
0 голосов
/ 07 ноября 2018

Я новичок в Angular. У меня следующая проблема: мне нужно отображать в таблице только строки со статусом == "ЗАВЕРШЕНО". Я понимаю, почему мой код работает не так, как я хочу, но не могу найти для меня правильного решения.

Вот файл .ts:

import { Component, OnInit } from '@angular/core';

 import { TestCase } from '../test-cases/models/test-case.model';
 import { TestCaseService } from '../test-case.service';

@Component({
  selector: 'app-test-cases-view',
  templateUrl: './test-cases-view.component.html',
  styleUrls: ['./test-cases-view.component.css']
})
export class TestCasesViewComponent implements OnInit {
  testCases: TestCase[];
  displayedColumns: string[] = ['testCaseName', 'testCaseDescription','id','created','status', 'xls'];
  constructor(private testCaseService: TestCaseService) { }

  ngOnInit() {
    this.getTestCases();
  }

  postRequest(testCaseId: string):void {
    this.testCaseService.postTestResult(testCaseId);
  }

  getTestCases(): void {
    this.testCaseService.getTestCases()
      .subscribe(testCases => this.testCases = testCases);
  }

}

файл test-case.model.ts:

import { TestCaseParams } from './test-case-params.model';

export class TestCase {
  public testCaseName:string;
  public testCaseDescription:string;
  public parameters:TestCaseParams;
  public id:string;

  constructor () {
    this.parameters= new TestCaseParams();
  }
}

тест-кейс-params.model.ts

import { EditedVar } from './replacement.model';
import { FilterVar } from './filter.model';
import { OutputVar } from './output.model';

export class TestCaseParams {
  public appsCount: number;
  public algId: number;
  public product: string;
  public invokeConsolidation: boolean;
  public invokeProdStrategy: boolean;
  public filterVars: FilterVar[];
  public editedVars: EditedVar[];
  public outputVars: OutputVar[];
  public fromDate: Date;
  public toDate:Date;
}

replacement.model.ts:

export class EditedVar {
  public path:string;
  public value:string;
}

filter.model.ts:

export class FilterVar{
  public filter:string;
  public filterType:string;
  public filterValue:string;
  public varch:boolean;
}

output.model.ts:

export class OutputVar {
  public path:string;
  public alias:string;
  public type:string;
}

Вот HTML-файл, который работает:

<div id="view-component">
  <h2>Test Cases</h2>

  *some code just don't fit in the question*

    <ng-container matColumnDef="xls">
      <th mat-header-cell *matHeaderCellDef> Xls report </th>
      <td mat-cell *matCellDef="let testCase">
        <button *ngIf = "testCase.status == 'FINISHED'" (click)="postRequest(testCase.id)">Make Excel report</button>
      </td>
    </ng-container>

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

Вот что я пытаюсь сделать:

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

    <ng-container *ngIf = "testCase.status == 'FINISHED'" matColumnDef="testCaseName">
      <th mat-header-cell *matHeaderCellDef> testCaseName </th>
      <td mat-cell *matCellDef="let testCase"> {{testCase.testCaseName}} </td>
    </ng-container>

    <ng-container *ngIf = "testCase.status == 'FINISHED'" matColumnDef="testCaseDescription">
      <th mat-header-cell *matHeaderCellDef> testCaseDescription </th>
      <td mat-cell *matCellDef="let testCase"> {{testCase.testCaseDescription}} </td>
    </ng-container>

    <ng-container *ngIf = "testCase.status == 'FINISHED'" matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef> Report Id </th>
      <td mat-cell *matCellDef="let testCase"> {{testCase.id}} </td>
    </ng-container>

    <ng-container *ngIf = "testCase.status == 'FINISHED'" matColumnDef="created">
      <th mat-header-cell *matHeaderCellDef> Created </th>
      <td mat-cell *matCellDef="let testCase"> {{testCase.created | date: 'dd/MM/yyyy hh:mm:ss'}} </td>
    </ng-container>

    <ng-container *ngIf = "testCase.status == 'FINISHED'" matColumnDef="status">
      <th mat-header-cell *matHeaderCellDef> Status </th>
      <td mat-cell *matCellDef="let testCase"> {{testCase.status}} </td>
    </ng-container>

    <ng-container *ngIf = "testCase.status == 'FINISHED'" matColumnDef="xls">
      <th mat-header-cell *matHeaderCellDef> Xls report </th>
      <td mat-cell *matCellDef="let testCase">
        <button (click)="postRequest(testCase.id)">Make Excel report</button>
      </td>
    </ng-container>

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

Как видите, я не хочу отображать строки с любым состоянием, которое не равно "ЗАВЕРШЕНО". Для этого кода я получаю следующую ошибку:

ОШИБКА TypeError: Невозможно прочитать свойство 'status' из неопределенного в Object.eval [as updateDirectives] (TestCasesViewComponent.html: 6)

Я понимаю, что мне нужно поместить let testCase где-то еще, чтобы он был определен на уровне ng-контейнера, но я не могу понять, где.

Ответы [ 2 ]

0 голосов
/ 08 ноября 2018

Вместо того чтобы выполнять фильтрацию на уровне mat-table, вы можете отфильтровать массив, полученный из Observable, и вместо этого назначить отфильтрованный массив в качестве данных:

getTestCases(): void {
  this.testCaseService.getTestCases()
    .subscribe(testCases => this.testCases = testCases.filter(({ status }) =>
      status === 'FINISHED',
  ));
}
0 голосов
/ 07 ноября 2018

Эта ошибка вызвана тем, что testCase равен undefined , а в javascript-файле при доступе к свойствам (таким как testCase.status) в неопределенном объекте всегда будет выбрасываться ошибка.

Но причина, по которой testCase не определена, заключается в том, что *ngIf будет запущен до , метод getTestCases()

У вас есть два возможных решения:

  1. Создание объекта;

  2. Используйте другой * ngIf, чтобы проверить, является ли testCase неопределенным.

Например:

    <div *ngIf="testCase">
       <div *ngIf="testCase.status == 'FINISHED'">

       </div>
    </div>

Другими словами, вам просто нужно быть уверенным, что testCase in не неопределен при доступе к его свойствам в *ngIf.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...