Angular:如何订阅@Input更改 [英] Angular: How to subscribe to @Input changes

查看:78
本文介绍了Angular:如何订阅@Input更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个角度组件,该组件使用提供的对象数组呈现html表.

I'm trying to create a angular component, which renders a html table using the provided object array.

我已经实现了OnChanges来检测对@Input的更改,但这似乎不起作用.

I have implemented OnChanges to detect changes to the @Input, it doesn't seem to work though.

为了进行测试,我正在使用setInterval添加一些数据,但是并没有反映在子组件中.

For testing, I'm using setInterval to add some data, but It's not getting reflected in the child component.

这是我到目前为止的代码,

This it the code I have so far,

ng-table.component.ts:

export class NgTableComponent implements OnInit, OnChanges {

    @Input() data: any[];

    private columns: string[];
    private rows: string[][];

    constructor() {
        this.columns = [];
        this.rows = [];
    }

    ngOnInit() {
    }

    ngOnChanges(changes: SimpleChanges) {
        console.log(changes);
        if (changes.data) {
            this.extractRowsAndColumns(this.data);
        }
    }

    extractRowsAndColumns(objArray: any[]): void {
        const colSet = new Set<string>();
        for (let i = 0; i < objArray.length; i++) {
            const keys = Object.keys(objArray[i]);
            for (let j = 0; j < keys.length; j++) {
                colSet.add(keys[j]);
            }
        }
        this.columns = Array.from(colSet);

        for (let i = 0; i < objArray.length; i++) {
            const obj = objArray[i];
            const row = [];
            for (let j = 0; j < this.columns.length; j++) {
                if (obj.hasOwnProperty(this.columns[j])) {
                    row.push(obj[this.columns[j]]);
                } else {
                    row.push(null);
                }
            }
            this.rows.push(row);
        }
    }
}

ng-table.component.html:

<div>
    <table class="ngtable">
        <tr>
            <th *ngFor="let col of columns">
                {{col}}
            </th>
        </tr>
        <tr *ngFor="let row of rows">
            <td *ngFor="let cell of row">{{cell}}</td>
        </tr>
    </table>
</div>

我正在app.component中使用上述组件

I'm using the above component in app.component

app.component.ts:

export class AppComponent {
  timer: any;
  count = 0;
  constructor() {
    const o: any = {
      'id': 1,
      'name': 'Jeanette',
      'last_name': 'Penddreth',
      'email': 'jpenddreth0@census.gov',
      'gender': 'Female',
      'ip_address': '26.58.193.2'
    };
    this.timer = setInterval(() => {
      this.data.push(o);
      console.log(this.data.length);
      if ( this.count++ === 5) {
        clearInterval(this.timer);
      }
    }, 1000 * 1);
  }

  data = [{
    'id': 1,
    'name': 'Jeanette',
    'last_name': 'Penddreth',
    'email': 'jpenddreth0@census.gov',
    'gender': 'Female',
    'ip_address': '26.58.193.2'
  }, {
    'id': 2,
    'name': 'Giavani',
    'last_name': 'Frediani',
    'email': 'gfrediani1@senate.gov',
    'gender': 'Male',
    'ip_address': '229.179.4.212'
  }, {
    'id': 3,
    'name': 'Noell',
    'last_name': 'Bea',
    'email': 'nbea2@imageshack.us',
    'gender': 'Female',
    'ip_address': '180.66.162.255'
  }, {
    'id': 4,
    'name': 'Willard',
    'last_name': 'Valek',
    'email': 'wvalek3@vk.com',
    'gender': 'Male',
    'ip_address': '67.76.188.26'
  }];
}

app.component.html:

<app-ng-table [data]="data"></app-ng-table>

@Input更改时如何更新组件?

How can I make the component update when @Input changes?

更新:我创建了一个显示以下内容的插件: https://plnkr.co/edit/szz1SNooQ1vIZhnFgiys?p=preview

UPDATE: I have created a plunkr demonstrating this: https://plnkr.co/edit/szz1SNooQ1vIZhnFgiys?p=preview

推荐答案

正如TimHovius所说,angular仅在进行参考检查.由于您要推送到同一数组,因此ng-table.component不会检测到更改(对输入的引用仍然相同).您可以做的一件事是创建数组的浅表副本.

As TimHovius stated, angular is only doing a reference check. Since you are pushing to the same array, the ng-table.component is not detecting a change (the reference to the input is still the same). One thing you can do is to create a shallow copy of the array.

addItem(): void {
    this.data.push(this.data[this.data.length-1]);
    // create shallow copy of array, since this is a new array (and new reference) ngOnChanges hook of the ng-table.component will fire
    this.data = this.data.slice(0);
}

现在ng-table.component将检测到输入已更改并触发ngOnChanges

Now ng-table.component will detect that the input has changed and fire ngOnChanges

这是一个plunkr演示此内容( https://plnkr.co/edit/2tdMEA9PLc2TEL4Gy4Lp? p = preview )

Here is a plunkr demoing this (https://plnkr.co/edit/2tdMEA9PLc2TEL4Gy4Lp?p=preview)

这篇关于Angular:如何订阅@Input更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆