[英]How to reuse the table component in angular2?
我是Angular2框架的新手。 我試圖在我的應用程序中重用單個表組件。 當我試圖這樣做時,面臨着重復在我的表行中進行任何形式的數組的困難。 我如何使我的表行迭代作為輸入傳遞到我的表組件的任何類型的數組。
當我將數組作為輸入傳遞給表組件時,是否可以重用表組件?
以下是我的代碼段。 我該如何重用它? 請建議我最好的方法。
app.component.html
<table>
<thead>
<td>name</td>
<td>empid</td>
</thead>
<tbody>
<tr *ngFor="let item of items;">
<td>{{item.name}}</td>
<td>{{item.empid}}</td>
</tr>
</tbody>
</table>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
items=[{name:"ravi",empid:"10215"},{name:"ravi",empid:"10215"},{name:"ravi",empid:"10215"},{name:"ravi",empid:"10215"},{name:"ravi",empid:"10215"}];
}
對於具有不同結構的類型的數組,您可以只創建一個管道並提取值(盡管這確實會增加大約一半的內存占用)
@Pipe({
name: 'objectValues'
})
export class ObjectValuesPipe implements PipeTransform {
transform(obj: any) {
let result = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
result.push(obj[key]);
}
}
return result;
}
}
在這里,我們只是從對象中提取值,然后將它們返回到數組中。
然后在你的桌子上,做
@Component({
selector: 'my-table',
template: `
<table>
<thead>
<td *ngFor="let header of headers">{{ header }}</td>
</thead>
<tbody>
<tr *ngFor="let item of items">
<td *ngFor="let value of item | objectValues">
{{ value }}
</td>
</tr>
</tbody>
</table>
`
})
export class TableComponent {
@Input() items
@Input() headers
}
也可以看看
ngFor
迭代地圖和對象。 當前不支持它,因此其他人提出了解決方法。 是的,您可以將表做成可重用的表組件:
table.component.ts
import {Component, Input} from '@angular/core';
@Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.css']
})
export class TableComponent {
@Input() items;
@Input() field1;
@Input() field2;
constructor() {
}
}
table.component.html
<table>
<thead>
<td>name</td>
<td>empid</td>
</thead>
<tbody>
<tr *ngFor="let item of items;">
<td>{{item[field1]}}</td>
<td>{{item[field2]}}</td>
</tr>
</tbody>
</table>
app.component.html
<app-table [items]="data" [field1]="field1" [field2]="field2"></app-table>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent{
// data: any[] = [{name: "ravi", empid: "10215"}, {name: "ravi", empid: "10215"}];
// field1: string = 'name';
// field2: string = 'empid';
field1: string = 'product';
field2: string = 'price';
data = [
{product: "mobile", price: "10215"},
{product: "camera", price: "10215"}
];
constructor() { }
ngOnInit() {
}
}
this.keys = Object.keys(this.data);
<tr *ngFor="let row of data">
<td *ngFor="let key of keys">
{{ row[key] }}
</td>
</tr>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.