是否有可能以編程方式在aurelia中創建組件,然後以某種方式將其綁定到視圖中該類型的標記。例如,像簡單的樹形視圖,請參閱下面的HTML模板中的註釋。以編程方式實例化Aurelia中的組件
樹view.ts
import {TreeNode} from "./tree-node";
export class TreeView<T> {
private _rootNodes: TreeNode<T>[] = [];
get rootNodes(): TreeNode<T>[] {
return this._rootNodes;
}
public addRootNode(node: TreeNode<T>) {
this._rootNodes.push(node);
}
}
樹node.ts
export class TreeNode<T> {
private _value: T;
private _name: string;
private _children: TreeNode<T>[] = [];
get value(): T {
return this._value;
}
get name(): string {
return this._name;
}
get children(): TreeNode<T>[] {
return this._children;
}
public addChild(child: TreeNode<T>): void {
this._children.push(child);
}
constructor(name: string, value: T) {
this._name = name;
this._value = value;
}
}
樹view.html
<template>
<!-- Something like this is the intend -->
<tree-node repeat.for="node of rootNodes"></tree-node>
</template>
樹node.html
<template>
<div>${name}</div>
<div class='childNodes'>
<!-- Something like this is the intend -->
<tree-node repeat.for="node of children"></tree-node>
</div>
</template>
您可以將它添加到DOM並對其調用「增強」,但是一般情況下,如果您試圖動態添加東西到DOM中,您就知道它們將要去哪裏,所以我建議使用'compose'自定義元素 –