我正在制作一个自定义组件来构建一个表。
export class TableComponent implements OnChanges {
@Input() records: any[];
@Input() caption: string;
@Input() config: TableConfig[];
}
export class TableConfig {
basePath: string;
actions?: object[];
}
//Actions example
/*
action = { icon: "", description: "", onClick: thisMustReceiveAFunction }
*/
我只是在我想要表格的地方调用我的组件
<my-table
[records]="entities"
[caption]="Table"
[config]="myConfig">
</my-table>
并在我的组件调用者
中初始化我的配置myConfig: TableConfig = {
basePath: "users",
actions: [
{
icon: "glyphicon glyphicon-pencil",
description: "edit",
onClick: this.MyEditFunction
},
{
icon: "glyphicon glyphicon-trash",
description: "delete"
onClick: this.MyDeleteFunction
}
]
};
MyEditFunction(): void { console.log('edit clicked'); }
MyDeleteFunction(): void { console.log('delete clicked'); }
但是当我尝试在我的桌面模板上打电话时,它不起作用。
<button class="btn btn-default" *ngFor="let action of config.actions" (click)="action.onClick()">
<span class="{{action.icon}}"></span>
</button>
答案 0 :(得分:1)
您应该使用类型安全运算符 ?
,因为即使在检索数据之前DOM也会呈现。
<button class="btn btn-default" *ngFor="let action of config?.actions"
(click)="action.onClick()">
<span class="{{action?.icon}}"></span>
</button>
或者您可以使用*ngIf
来确保如果数据不可用,则不会加载DOM,
<span *ngIf="config.actions.length > 0">
<button class="btn btn-default" *ngFor="let action of config.actions" (click)="action.onClick()">
<span class="{{action.icon}}"></span>
</button>
</span>