问题是关于使用TypeScript和Angular(6)
我有一个模型课:
export class DropData {
private readonly _originType: Component;
private readonly _originRow: number;
private readonly _originCol: number;
private readonly _originComp: number;
constructor(originType: Component, originRow: number, originCol: number, originComp: number) {
this._originType = originType;
this._originRow = originRow;
this._originCol = originCol;
this._originComp = originComp;
}
export class Component {
id: number;
component: string;
constructor(id: number, component: string) {
this.id = id;
this.component = component;
}
}
是否可以通过HTML模板初始化此方法?我尝试了以下操作,但似乎不起作用:
<div mwlDraggable
[ghostElementTemplate]="dragging"
[dropData]="new DropData(new PageComponent(component.id, componentManager.getComponentSimpleName(component.id)),rowIndex, colIndex, compIndex)"
dragActiveClass="drag-active">
<ng-template
[appComp]="componentManager.getComponentSimpleName(component.id)"
[id]="component.id">
</ng-template>
</div>
( EDIT :我省略了函数'componentManager.getComponentSimpleName(component.id)',它返回了一个字符串并可以正常工作)< / p>
EDIT2 访问页面时的堆栈跟踪:
Uncaught Error: Template parse errors:
Parser Error: Unexpected token 'DropData' at column 5 in [new DropData(new
PageComponent(component.id, componentManager.getComponentSimpleName(component.id)),rowIndex, colIndex, compIndex)] in ng:///AppModule/PageFoundationComponent.html@80:21 (" <div mwlDraggable
[ghostElementTemplate]="dragging"
[ERROR ->][dropData]="new DropData(new
PageComponent(component.id, componentManager.getComponentSimpleName(comp"): ng:///AppModule/PageFoundationComponent.html@80:21
答案 0 :(得分:1)
模板无法立即访问全局变量。
您基本上无法访问模板中不是组件属性的任何内容。因此,在这种情况下,您的组件将需要:
public DropData: any = DropData;
这类似于您访问模板中的枚举的方式。 componentManager
也会有类似的问题。您需要做这种事情的事实说明了为什么在模板中包含这样的代码是一个糟糕的选择。模板表示如何显示组件数据。组件本身负责创建/获取/提供该数据。