我想创建一个角度组件,它使用提供的对象数组呈现一个html表。Angular:如何订阅@Input变化
我已经实施OnChanges
来检测@Input
的变化,但它似乎并没有工作。
对于测试,我使用setInterval
来添加一些数据,但它没有反映在子组件中。
这一点,我的代码到目前为止,
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中使用了上述组件
个app.component.ts:
export class AppComponent {
timer: any;
count = 0;
constructor() {
const o: any = {
'id': 1,
'name': 'Jeanette',
'last_name': 'Penddreth',
'email': '[email protected]',
'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': '[email protected]',
'gender': 'Female',
'ip_address': '26.58.193.2'
}, {
'id': 2,
'name': 'Giavani',
'last_name': 'Frediani',
'email': '[email protected]',
'gender': 'Male',
'ip_address': '229.179.4.212'
}, {
'id': 3,
'name': 'Noell',
'last_name': 'Bea',
'email': '[email protected]',
'gender': 'Female',
'ip_address': '180.66.162.255'
}, {
'id': 4,
'name': 'Willard',
'last_name': 'Valek',
'email': '[email protected]',
'gender': 'Male',
'ip_address': '67.76.188.26'
}];
}
app.component.html:
<app-ng-table [data]="data"></app-ng-table>
我怎样才能使组件更新时@Input
变化?
更新:我创建了一个plunkr证明这一点:https://plnkr.co/edit/szz1SNooQ1vIZhnFgiys?p=preview
参照本[尝试的可观察输入* * answer **](https://stackoverflow.com/questions/44467336/observable-of-input-property/44467942#44467942) – Aravind
有兴趣的人可以在这里看看完整的代码:https:// github .com/cyberpirate92/ngTable – cyberpirate92