【问题标题】:*ngIf doesn't work in an an Angular Material table when using an observable*ngIf 在使用 observable 时在 Angular Material 表中不起作用
【发布时间】:2019-05-02 10:48:12
【问题描述】:

我正在尝试使用具有可扩展行的 Angular Material 表,仅当屏幕宽度低于特定断点时才显示信息。我正在使用我在 HTML 中订阅的可观察的isHandSetPortrait$ 来确定是否已到达断点。

该表有两列(Name 和 Info)。 Name 无论isHandsetPortrait 是真还是假都会显示,Info 仅在isHandsetPortrait$ 为false 时显示。这按预期工作。

在可扩展行中,我有一个*ngIf,它使用相同的可观察isHandsetPortrait$,当isHandsetPortrait$ 的输出为true 时显示文本。但是,这似乎不起作用。

table-expandable-rows-example.html

<!-- *ngIf works here -->
  <div *ngIf="isHandsetPortrait$ | async">ngIf works here</div>
  <div class="mat-elevation-z8">
    <table mat-table [dataSource]="dataSource" matSort matSortActive="priority" matSortDirection="desc"
           multiTemplateDataRows>


      <!-- Name Column -->
      <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> Name</th>
        <td mat-cell *matCellDef="let row"> {{row.name}}</td>
      </ng-container>

      <!-- Info Column -->
      <ng-container matColumnDef="info" >
        <th mat-header-cell *matHeaderCellDef></th>
        <td mat-cell *matCellDef="let row" class="info-cell">
          Info
        </td>
      </ng-container>

      <!-- Expanded Content Column - The detail row is made up of this one column that spans across all columns -->
      <ng-container matColumnDef="expandedDetail">
        <td mat-cell *matCellDef="let element" [attr.colspan]="displayedColumns.length">
          <div class="expanded-content" [@detailExpand]="element == expandedElement ? 'expanded' : 'collapsed'">
            Additional text....
            <!-- *ngIf does not work here -->
            <div *ngIf="isHandsetPortrait$ | async">ngIf does not work here</div>
          </div>
        </td>
      </ng-container>

      <tr mat-header-row *matHeaderRowDef="getDisplayedColumns(isHandsetPortrait$ | async)"></tr>
      <tr mat-row *matRowDef="let element; columns: getDisplayedColumns(isHandsetPortrait$ | async);"
          class="example-element-row" [class.example-expanded-row]="expandedElement === element"
          (click)="expandedElement = expandedElement === element ? null : element"></tr>
      <tr mat-row *matRowDef="let row; columns: ['expandedDetail']" class="example-detail-row"></tr>
    </table>
  </div>

table-expandable-rows-example.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, MatSort, MatTableDataSource } from '@angular/material';
import { animate, state, style, transition, trigger } from '@angular/animations';
import { from, Observable, of, pipe } from 'rxjs';
import { concatMap, delay, map, share } from 'rxjs/operators';
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';

/**
 * @title Table with expandable rows
 */
@Component({
  selector: 'table-expandable-rows-example',
  styleUrls: ['table-expandable-rows-example.css'],
  templateUrl: 'table-expandable-rows-example.html',
animations: [
    trigger('detailExpand', [
      state('collapsed', style({ height: '0px', minHeight: '0' })),
      state('expanded', style({ height: '*' })),
      transition('expanded <=> collapsed', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)'))
    ]),
  ]
})
export class TableExpandableRowsExample {

    public isHandsetPortrait$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.HandsetPortrait)
    .pipe(
      map(orientationState => orientationState.matches),
      share()
    );

  private chatRequests = [
    {
      name: 'John Wayne'
    },
    {
      name: 'Oscar Wilde'
    },
    {
      name: 'Eric Cantona'
    }
  ];

  dataSource = new MatTableDataSource(this.chatRequests);

  displayedColumns: { def: string, isMobile: boolean }[] = [
    {
      def: 'name',
      isMobile: true
    },
    {
      def: 'info',
      isMobile: false
    }
  ];

  constructor(private breakpointObserver: BreakpointObserver) { }


  public getDisplayedColumns(isHandsetPortrait: boolean) {
    return this.displayedColumns
      .filter(cd => !isHandsetPortrait || cd.isMobile)
      .map(cd => cd.def);
  }

}

我已经整理了一个StackBlitz project,应该可以突出我遇到的问题。

*ngIf 在表格外部工作(html 模板的第 2 行),但在表格内部不起作用(html 模板的第 28 行)。如何使第二个*ngIf 工作?

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    您必须使用 shareReplay 才能使其正常工作,使用 share 第二个订阅者不会发生任何事情

    public isHandsetPortrait$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.HandsetPortrait)
    .pipe(
      map(orientationState => orientationState.matches),
      shareReplay(1) // here
    );
    

    https://stackblitz.com/edit/angular-ml4vym-71mba5

    【讨论】:

    • 完美,非常感谢!我从根本上误解了share() 的工作原理;将我的代码更改为您的解决方案为我修复了它。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2023-01-19
    相关资源
    最近更新 更多