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

Angular 数据源更改时角度2子组件不更新,angular,typescript,parent-child,single-page-application,angular2-docheck,Angular,Typescript,Parent Child,Single Page Application,Angular2 Docheck,我已经创建了一个表组件,它根据我传入的配置生成一个表。我知道可能有更好的方法来编写一个可重用组件,但现在这就是我所拥有的 基本上,该组件采用带有列和数据源对象的配置,然后将列映射到数据源中的属性 我的问题是,在某个时刻,我更改了表的一个数据源,我首先清空了数组,例如 this.members.datasource = [] 然后我将新数据推送到数据源上,就像这样 for (let member in members) { this.members.datasource.

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

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

我的问题是,在某个时刻,我更改了表的一个数据源,我首先清空了数组,例如

this.members.datasource = []
然后我将新数据推送到数据源上,就像这样

for (let member in members) {
            this.members.datasource.push(members[member]);
}
我的问题是,执行此操作时,表不会使用数据源中的新数据进行更新

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

以下是所有相关代码和标记

ip数据表组件

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>

{{column.header}}
{{item[column.mapKey]}
利用ip数据表的组件

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]);
        }
    }
}
<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>
import{Component,OnInit,AfterViewInit,ApplicationRef}来自“@angular/core”;
从“@angular/router”导入{ActivatedRoute}”;
从“../../services/engagement.service”导入{EngagementService};
从“../../models/index”导入{EngagementEditModel}”;
从“../../core/components/ip datatable/interfaces/index”导入{ITable}”;
@组成部分({
templateUrl:“约定上下文.组件.html”
})
导出类EngagementContextComponent{
公共id:string;
公共参与详细信息:参与编辑模型;
//暂时硬编码组,因为只有两个可用组。
公共组:ITable={
栏目:[
{
标题:“姓名”,
映射键:“名称”
}
],
行配置:{
类:“可点击覆盖”
},
数据源:[
{
名称:“业主”
},
{
名称:“用户”
}]
};
公共成员:ITable={
栏目:[
{
标题:“姓名”,
映射键:“名称”
}
],
数据源:[]
}
构造函数(私有engagementService:engagementService,私有路由:ActivatedRoute,私有appRef:ApplicationRef){
this.id=route.snapshot.params[“id”];
this.engagementService.getengagementedittailsbyid(parseInt(this.id))
.然后((数据:EngagementEditModel)=>{
this.engagementDetails=数据;
console.log(this.engagementDetails);//tslint:禁用行
});
}
已单击的公共组(e:事件){
//获取事件的元素
设elem:IEventElement=e.currentTarget;
//获取所选节点的名称
让groupName=elem.textContent.trim().toLowerCase();
让成员=(this.engagementDetails)[groupName];
接口IEventElement扩展了EventTarget{
文本内容?:字符串;
}
this.members.datasource=[];
for(让成员加入成员){
this.members.datasource.push(members[member]);
}
}
}
ip数据表的HTML用法

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]);
        }
    }
}
<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>

组
成员

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


鉴于我听说过ngDoCheck的性能障碍,如果我开始注意到性能缺陷,我可能会采取其他措施。如果有人能在评论中对此有所了解,我将不胜感激。

您可以使用ChangedetectionStartegy.onPush(),因为这会自动刷新数据,并在数据源更改时检测更改,并通知用户界面,也可以考虑将数据源声明为一个数组。

你能把你的答案更新到正确的代码吗?@ McCalulu:对不起,这是很久以前我丢失的代码了。如果您遇到问题,请随时联系我。我认为最好的方法是引用childView并调用refresh()函数来重新分配变量