【问题标题】:Transclude Component and still use ngFor转入组件并仍然使用 ngFor
【发布时间】:2017-07-06 14:14:26
【问题描述】:

我正在尝试在从 API 返回的数据数组上模拟分页。 这对我来说非常适合我,但是我需要做的是在其中嵌套另一个使用 ngFor 的组件,它的 ngFor 数据从我的嵌入组件传递下来。

如果我在我的嵌入组件中运行调试器,我可以看到我的完整数组进入,我还可以看到它被拼接并创建了一个包含我已经变异的数据的新对象。

但是,当我尝试使用 ngFor 渲染组件并传入新数组时,没有渲染任何内容。

我还向这个组件添加了一个调试器,它似乎根本没有被触发,因为调试器甚至没有触发。

我的代码如下:

object-transclusion.component.ts

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

@Component({
    selector: 'app-object-transclusion',
    template: '<ng-content></ng-content>'
})

export class ObjectTransclusionComponent implements OnInit {

    @Input() items: any;

    public pageNo: number = 1;
    public paginatedItems: string[];

    private results_per_page: number = 1;
    private totalPages: number;

    ngOnInit() {
        this.totalPages = this.getMaxPages();
        this.updatePaginationState();
    }

    public nextPage(): void {
        if (this.pageNo < this.totalPages) {
            this.pageNo++;
            this.updatePaginationState();
        }
    }

    public prevPage(): void {
        if (this.pageNo > 1) {
            this.pageNo--;
            this.updatePaginationState();
        }
    }

    private updatePaginationState(): void {
        this.paginatedItems = [
            ...this.items.slice(
                (this.pageNo - 1) * this.results_per_page, this.pageNo * this.results_per_page
            )
        ];
    }

    private getMaxPages(): number {
        return Math.ceil(this.items.length / this.results_per_page);
    }
}

event-table.component.pug

.event-table-container
    life-event-table-header
    app-object-transclusion([items]='events')
        life-event-table-row(*ngFor='let event of paginatedItems', [event]='event', [canModifyLifeEvents]='canModifyLifeEvents')

如何在transclusion组件中对数据进行排序,使其可用于通过 ng-content 渲染的组件?

【问题讨论】:

    标签: angular transclusion


    【解决方案1】:

    好的,看起来解决方案是向

    添加一个本地模板变量
    app-object-transclusion(#transclude [items]='events')
    

    这允许我使用

    输出数据
    *ngFor='let event of transclude.paginatedItems'
    

    不像我喜欢的那样优雅,但它很有效。

    【讨论】:

      猜你喜欢
      • 2018-02-14
      • 2017-03-04
      • 1970-01-01
      • 2016-05-19
      • 2016-02-23
      • 1970-01-01
      • 1970-01-01
      • 2017-04-18
      • 2018-02-22
      相关资源
      最近更新 更多