I'm using angular v9. I'm creating a component and the parameters is a list of items and a callback, in ngOnInit, i call the function group and i reduce the items parameter, and every item, i call the callback and in my app i just return the item i want to group.
Some part of code:
HTML - Component
<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>
Typescript - Component
@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;
}, {});
}
And my usage of component:
HTML - Component usage
<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>
Typescript - Component Usage
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;
}
So i got this error when i running my component
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: '[object Object]'.
My expecation is work without error, because the component is working very well, but have this error... i already try to change to static: true, in @ContentChild, and create embedViews but not works..