我有一个显示静态数据的简单表格,但是,我有通过input
显示它的问题。
问题是如何使用item
输入将数据传递到material2表。
export class InvoiceItemComponent implements OnInit {
displayedColumns = ['id', 'description', 'amount', 'taxGroup'];
exampleDatabase = new ExampleDataBase();
dataSource: ExampleDataSource | null;
@Input() item;
constructor() {}
ngOnInit() {
console.log(this.exampleDatabase.data);
this.dataSource = new ExampleDataSource(this.exampleDatabase);
}
}
export class ExampleDataBase {
dataChange: BehaviorSubject<any> = new BehaviorSubject([]);
get data(): InvoiceItem[] {
return [ // works fine with static data, cannot figure out how to pass it via @Input() item which is the required data
{
id: 1,
description: 'your desc here',
amount: 20,
taxAmount: 20,
taxGroup: {
id: 1,
name: 'tax group name'
}
},
];
}
constructor() {
this.dataChange.next(this.data);
}
}
export class ExampleDataSource extends DataSource<any> {
constructor(private _exampleDatabase: ExampleDataBase) {
super();
}
/** Connect function called by the table to retrieve one stream containing the data to render. */
connect(): Observable<InvoiceItem[]> {
console.log(this._exampleDatabase.dataChange);
return this._exampleDatabase.dataChange;
}
disconnect() {}
}
答案 0 :(得分:1)
也许尝试这样的事情
export class InvoiceItemComponent implements OnInit {
displayedColumns = ['id', 'description', 'amount', 'taxGroup'];
dataSource: InvoiceItemDataSource | null;
@Input() set items(vals: InvoiceItem[]) {
this.itemSubject.next(vals);
}
/** Emits a new array of invoice items whenver `@Input() items` changes */
itemSubject = new BehaviorSubject<InvoiceItem[]>([]);
constructor() {}
ngOnInit() {
// Pass the item subject as an observable which can be connected directly
// to the data source's `connect()`
this.dataSource = new InvoiceItemDataSource(this.itemSubject.asObservable());
}
}
export class InvoiceItemDataSource extends DataSource<any> {
constructor(private data: Observable<InvoiceItem[]>) {
super();
}
connect(): Observable<InvoiceItem[]> {
return this.data;
}
disconnect() {}
}