簡體   English   中英

數據源更改時,Angular 2子組件未更新

[英]Angular 2 child component not updating when datasource changes

我已經創建了一個表組件,該表組件會根據傳入的配置生成一個表。我知道可能存在更好的編寫可重用組件的方法,但是現在這就是我所擁有的。

基本上,組件采用帶有列和數據源對象的配置,然后將列映射到數據源中的屬性。

我的問題是,在某個時候我更改了表的數據源之一,例如,我首先清空了數組。

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>

好的,所以我的問題是在ngOnInit中,我將此this.config.datasource分配給一個名為tableData的變量。 好吧,當更改發生時,它永遠不會重新分配給該變量,因此,通過調用ngDoCheck函數,然后將this.config.datasource分配給tableData,我就可以根據需要反映更改。

考慮到我聽說過ngDoCheck的性能障礙,如果我開始注意到性能缺陷,我可能會做其他事情。 如果有人可以在評論中對此有所了解,我將不勝感激。

您可以使用ChangedetectionStartegy.onPush(),因為這會自動刷新數據並在數據源發生變化並通知UI時檢測到變化,因此也可以考慮將數據源聲明為數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM