我试图从this example ag-grid学习,以便在网格的每一行中创建一个删除按钮。上述示例正在运行,但我的代码不是,我无法弄清楚原因。
我附上我的代码,希望有人可以帮助我。
home.component.ts:
@Component({
selector: 'home',
providers: [
Title
],
styleUrls: [ './home.component.css' ],
templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
private items: Item[] = [];
private gridOptions:GridOptions;
private columnDefs = [];
constructor(
private itemsService: ItemsService
) {
this.gridOptions = {};
this.columnDefs = this.createColumnDefs();
}
remove() {
alert("yey!")
}
ngOnInit(){
this.itemsService
.getAll()
.subscribe(result => {
this.items = result;
});
}
private createColumnDefs() {
return [
{
headerName: "Foo",
field: "foo",
width: 100,
},
{
headerName: "Bar",
field: "bar",
width: 100,
},
{
headerName: "",
field: "_id",
cellRendererFramework: RemoveButton,
colId: "params",
width: 100
},
];
}
}
home.component.html:
<div>
<ag-grid-angular #agGrid style="width: 602px; height: 350px;" class="ag-fresh"
[gridOptions]="gridOptions"
[columnDefs]="columnDefs"
[rowData]="items">
</ag-grid-angular>
</div>
RemoveButton.ts:
@Component({
selector: 'remove-button',
template: `<span><button style="height: 20px" (click)="remove()">X</button></span>`
})
export class RemoveButton implements ICellRendererAngularComp {
public params: any;
agInit(params: any): void {
this.params = params;
}
public remove() {
this.params.context.componentParent.remove();
}
}
显示网格包含所有数据,但单击该按钮会产生此错误:
ERROR TypeError: Cannot read property 'componentParent' of undefined
at RemoveButton.webpackJsonpac__name_.453.RemoveButton.remove
意味着context
的{{1}}未定义。
如果需要更多代码或信息,请告知我们。
答案 0 :(得分:3)
我已经解决了我的问题。显然context
未定义,因为我没有定义它。在gridOptions
中定义上下文已经解决了:
this.gridOptions ={
context: {
componentParent: this
}
};