我正在尝试创建一个表组件,该组件将从列描述和原始数据构建一个表。
我能够毫无问题地创建基本功能,但是我也希望能够覆盖单个单元格的默认呈现,以便能够显示自定义内容(例如,显示链接)。
以与DataTables相似的方式,唯一的区别是,我希望能够为带有参数的自定义组件传递名称。
我最初的尝试是这样的,但问题是,如果我在列的显示函数中实例化该组件,则无法在页面上显示它。
@Component({
selector: 'gt-table',
template: `
<table class="table table-striped table-hover">
<thead>
<tr>
<th *ngFor="#column of columns">
{{ column.title }}
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="#row of data">
<td *ngFor="#column of columns">
{{ displayCell(row, column) }}
</td>
</tr>
</tbody>
</table>
`
})
export class GTTableComponent implements {
@Input() data:Array<any>;
@Input() columns:Array<any>;
displayCell(row, column) {
if (column.display !== undefined) {
return column.display(row[column.name], row);
} else {
return row[column.name];
}
}
}
在Internet上搜索之后,我发现要在视图中动态加载组件,您需要使用DynamicComponentLoader。
经过很多头痛和搜索之后,即使它不是最漂亮的,我仍然能够找到与我在此响应中寻找的东西类似的东西。
我唯一剩下的问题是如何传递参数?我找不到有关使用参数动态加载组件的单个参考。任何帮助或建议?
解决方案:
因此,解决方案是使用DynamicComponentLoader
其loadIntoLocation
功能。这样做loadAsRoot
会比较理想,但是从2.0.0-beta.7
它的状态来看,它有很多问题,并且您无法根据promise设置实例属性。
因此,我要做的是为单元格创建一个组件,在其中确定是否需要实例化默认显示组件或用户是否要处理它:
import {Component, Input, OnInit, ElementRef, DynamicComponentLoader,
ComponentRef} from 'angular2/core';
import {GTTableDefaultDisplayComponent} from './gt-tabledefaultdisplay.component';
@Component({
selector: '[gt-cell]',
template: `<div #content></div>`,
directives: []
})
export class GTTableCellComponent implements OnInit {
@Input() row:any;
@Input() column:any;
constructor(private _loader: DynamicComponentLoader, private _elementRef: ElementRef) {
}
ngOnInit() {
if (this.column.display !== undefined) {
this.column.display(this._loader, this._elementRef, 'content',
this.row[this.column.name],this.row);
} else {
this._loader.loadIntoLocation(GTTableDefaultDisplayComponent,
this._elementRef, 'content').then((compRef:ComponentRef) => {
compRef.instance['content'] = this.row[this.column.name];
});
}
}
}
因此,使用属性加载动态组件的方法是将其设置为使用所返回的Promise compRef:ComponentRef
。这将是一个变量,您可以在其中访问新创建的组件的实例,compRef.instance
并将其用作设置其变量的数组。
我的默认视图组件是如此简单:从“ angular2 / core”导入{Component,Input};
import {GTTableLinkComponent} from './gt-tablelink.component';
@Component({
selector: 'default-display',
template: `<div>{{content}}</div>`,
directives: []
})
export class GTTableDefaultDisplayComponent {
@Input() content:string;
constructor() {
}
}
我希望这也会对其他人有所帮助。
您可以使用返回的承诺loadAsRoot
(或loadNextToLocation
或loadIntoLocation
)方法来访问它的新组件实例,并集合中的元素:
dcl.loadAsRoot(ChildComponent, '#child',
injector).then((compRef:ComponentRef) => {
// For example
compRef.param1 = 'something';
// In your case
compRef.data = [
{ ... },
{ ... },
{ ... }
];
compRef.columns = [
'column1', 'column2'
];
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句