首页 > 解决方案 > 检查后表达式已更改 - ngTemplateOutletContext

问题描述

我正在使用角度 v9。我正在创建一个组件,参数是项目列表和回调,在 ngOnInit 中,我调用函数组并减少项目参数,每个项目,我调用回调,在我的应用程序中我只返回项目我想分组。

部分代码:
HTML - 组件

<div class="c-timeline">
  <div class="c-timeline__keys" *ngFor="let key of groupedKeys; let i = index">
    <div class="c-timeline__key">
      <ng-template [ngTemplateOutlet]="timelineKey" [ngTemplateOutletContext]="{key: key}"></ng-template>

      <div class="c-timeline__content-divider" *ngIf="i !== groupedKeys.length - 1">
        <div class="c-timeline__divider"></div>
      </div>
    </div>

    <div class="c-timeline__items">
      <div class="c-timeline__item" *ngFor="let item of groupedItems[key]">
        <ng-template [ngTemplateOutlet]="timelineValues" [ngTemplateOutletContext]="{item: item}"></ng-template>
      </div>
    </div>
  </div>
</div>

打字稿 - 组件

  @Input() public items: any[];
  @Input() public groupBy: Function;

  public groupedItems: any;
  public groupedKeys: string[];

  @ContentChild('timelineKey', {static: false}) timelineKey: TemplateRef<any>;
  @ContentChild('timelineValues', {static: false}) timelineValues: TemplateRef<any>;

  constructor() {
  }

  ngOnInit(): void {
    this.groupedItems = this.group();
    this.groupedKeys = Object.keys(this.groupedItems);
  }

  private group(): any {
    return this.items.reduce((acc, item, index) => {
      const key = this.groupBy({item, index});

      if (key in acc) {
        acc[key].push(item);
      } else {
        acc[key] = [item];
      }

      return acc;
    }, {});
  }

还有我对组件的使用:
HTML - 组件使用

<my-component [items]="items" [groupBy]="groupBy">
  <ng-template let-key="key" #timelineKey>
    <h4>{{ key }}</h4>

    <ng-template let-item="item" #timelineValues>
      {{ item.name}}
    </ng-template>
  </ng-template>
</my-component>

打字稿 - 组件使用

  public items: { name: string; id: number }[] = [
    {
      id: 1,
      name: 'Foo (id = 1)'
    },
    {
      id: 1,
      name: 'Banana Test (id = 1)'
    },
    {
      id: 2,
      name: 'Apple Test (id = 2)'
    },
    {
      id: 3,
      name: 'Lemon Test (id = 3)'
    },
    {
      id: 4,
      name: 'Grape Test (id = 4)'
    },
  ];

  public groupBy({item, index}): number {
    return item.id;
  }

所以我在运行我的组件时遇到了这个错误

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: '[object Object]'.

我的期望是没有错误的工作,因为该组件工作得很好,但是有这个错误......我已经尝试在@ContentChild中更改为静态:true,并创建embedViews但不起作用..

标签: angularangular-templateangular-template-variable

解决方案


推荐阅读