我正在尝试使用一个组件,该组件的模板引用了其中同一组件的另一个实例。
模型是这样的:
class Item {
String name;
Item(this.name);
}
class Box extends Item {
Box(String name) : super(name);
List<Item> contents = [];
}
基于上述,创建数据如下:
myBox = new Box('top box');
myBox.contents.add(new Item('level 2 - 1'));
myBox.contents.add(new Item('level 2 - 2'));
Box myBox2 = new Box('inner box');
myBox2.contents.add(new Item('level 3 - 1'));
myBox2.contents.add(new Item('level 3 - 2'));
myBox.contents.add(myBox2);
表示为 JSON,如下所示:
{
"name": "top box",
"contents": [
{"name": "level 2 - 1"},
{"name": "level 2 - 2"},
{"name": "inner box",
"contents": [
{"name": "level 3 - 1"},
{"name": "level 3 - 2"}
]
}
]
}
组件 dart (box_component.dart):
@Component(
selector: 'box-component',
templateUrl: 'box_component.html',
directives: const[CORE_DIRECTIVES]
)
class BoxComponent implements OnInit {
@Input()
Box box;
List contents =[];
ngOnInit() {
contents = box.contents;
}
isBox(Item itm) => (itm is Box);
}
组件模板(box_component.html):
<div *ngIf="box != null" style="font-weight: bold">{{box.name}}</div>
<div *ngFor="let item of contents">
{{item.name}}
<div *ngIf="isBox(item)">
This is a box
<box-component [box]="item"></box-component>
</div>
<div *ngIf="!isBox(item)">
This is an item
</div>
</div>
请注意,盒子组件的另一个实例嵌套在顶级盒子组件中 但是,渲染时,仅渲染顶级框的内容,而不渲染嵌套在其中的框内包含的内容。
看起来像这样:
顶盒
2 - 1 级
这是一个项目
2 - 2 级
这是一个项目
内盒
这是一个盒子
这是一个项目
有没有办法实现递归嵌套渲染?
最佳答案
模板使用的任何指令都必须在指令列表中声明。如果它想递归地使用自身,则这包括自身。所以在你的情况下 @Component 注释应该是:
@Component(
selector: 'box-component',
templateUrl: 'box_component.html',
directives: const[CORE_DIRECTIVES, BoxComponent]
)
class BoxComponent
关于dart - 递归使用组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47892071/