我想創建一個角度組件,它使用提供的對象數組呈現一個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