数据源更改时Angular 2子组件不更新

问题描述 投票:1回答:2

我已经创建了一个表组件,它根据我传入的配置生成一个表。我知道有可能更好的方法来编写一个可重用的组件,但是现在这就是我所拥有的。

基本上,组件采用带有列和数据源对象的配置,然后将列映射到数据源中的属性。

我的问题是,在某些时候我更改了一个表的数据源,我首先清空数组...

this.members.datasource = []

然后我将新数据推送到数据源,就像这样......

for (let member in members) {
            this.members.datasource.push(members[member]);
}

我的问题是,当我这样做时,表不会使用数据源中的新数据进行更新。

我在我的组件中使用了ngDoCheck函数,它确实在我更改数据源时触发,但没有其他任何事情发生。

这是所有相关代码和标记......

ip-datatable组件

import { Component, Input, Output, OnInit, EventEmitter, ElementRef, DoCheck } from "@angular/core";

import { ITable } from "./interfaces/index";

@Component({
    selector: "ip-datatable",
    templateUrl: "./ip-dataTable.component.html"
})
export class IpDataTableComponent implements OnInit, DoCheck {
    @Input()
    public config: ITable;
    public tableData: any;

    @Output()
    private onRowClick = new EventEmitter();

    constructor(private elem: ElementRef) {

    }

    public ngOnInit() {
        // TODO: Decide whether or not to make this more dynamic (ie: excepts functions returning things other than a promise)
        if (typeof (this.config.datasource) == "function") {
            this.config.datasource()
                .then((data: any) => {
                    this.tableData = data;
                });
        } else {
            this.tableData = this.config.datasource;
        }
    }

    public rowClicked(e:Event) {
        this.onRowClick.emit(e);
    }

    public ngDoCheck() {

    }
}

ip-datatable组件的模板html

<table class="table table-bordered table-hover">
    <thead>
    <tr>
        <td *ngFor="let column of config.columns">{{column.header}}</td>
    </tr>
    </thead>
    <tbody>
    <tr 
        *ngFor="let item of tableData" 
        [class]="(config.rowConfig !== undefined) ? config.rowConfig.classes : ''" 
        (click)="rowClicked($event)" [id]="(item.id !== undefined) ? item.id : ''">
        <td *ngFor="let column of config.columns">{{item[column.mapKey]}}</td>
    </tr>
    </tbody>
</table>

利用ip-datatable的组件

import { Component, OnInit, AfterViewInit, ApplicationRef } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { EngagementService } from "../../services/engagement.service";

import { EngagementEditModel } from "../../models/index";
import { ITable } from "../../core/components/ip-datatable/interfaces/index";

@Component({
    templateUrl: "engagement-context.component.html"
})

export class EngagementContextComponent {
    public id: string;
    public engagementDetails: EngagementEditModel;

    // Temporarily hardcode groups as there is only two available.
    public groups: ITable = {
        columns: [
            {
                header: "Name",
                mapKey: "name"
            }
        ],
        rowConfig: {
            classes: "clickable override"
        },
        datasource: [
        {
            name: "Owners"
        },
        {
            name: "Users"
        }]
    };

    public members: ITable = {
        columns: [
            {
                header: "Name",
                mapKey: "name"
            }
        ],
        datasource: []
    }

    constructor(private engagementService: EngagementService, private route: ActivatedRoute, private appRef: ApplicationRef) {
        this.id = route.snapshot.params["id"];
            this.engagementService.getEngagementEditDetailsById(parseInt(this.id))
            .then((data: EngagementEditModel) => {
                this.engagementDetails = data;
                console.log(this.engagementDetails); // tslint:disable-line
            });
    }

    public groupClicked(e: Event) {
        // Get the element of the event
        let elem: IEventElement = e.currentTarget;
        // Get the name of the selected node
        let groupName = elem.textContent.trim().toLowerCase();
        let members = (<any>this.engagementDetails)[groupName];

        interface IEventElement extends EventTarget {
            textContent?: string;
        }

        this.members.datasource = [];

        for (let member in members) {
            this.members.datasource.push(members[member]);
        }
    }
}

ip-datatable的HTML用法

<div class="row">
        <div class="col-md-12">
            <section class="section">
                <div class="section-body">
                    <h4 class="section-title">Groups</h4>
                    <ip-datatable
                        [config]="groups"
                        (onRowClick)="groupClicked($event)">
                    </ip-datatable>
                </div>
            </section>
        </div>
        <div class="col-md-12">
            <section class="section">
                <div class="section-body">
                    <h4 class="section-title">Members</h4>
                    <ip-datatable
                        [config]="members"
                    ></ip-datatable>
                </div>
            </section>
        </div>
    </div>
angular typescript parent-child single-page-application angular2-docheck
2个回答
3
投票

好吧,所以我的问题是在ngOnInit中我将this.config.datasource分配给一个名为tableData的变量。好吧,当更改发生时,它永远不会被重新分配给该变量,因此通过调用ngDoCheck函数然后将this.config.datasource分配给tableData我得到的反映就像我想要的那样。

鉴于我已经听说过ngDoCheck的性能障碍,如果我开始注意性能缺陷,我可能会做其他事情。如果有人可以在评论中对此有所了解,我会很感激。


1
投票

您可以使用ChangedetectionStartegy.onPush(),因为这会自动刷新数据并在数据源发生更改时检测更改并通知UI相同,还可以考虑将数据源声明为数组。

© www.soinside.com 2019 - 2024. All rights reserved.