我正在尝试使用一个组件,该组件的模板引用其中的同一组件的另一个实例。
该模型是这样的:
class Item {
String name;
Item(this.name);
}
class Box extends Item {
Box(String name) : super(name);
List<Item> contents = [];
}
Run Code Online (Sandbox Code Playgroud)
基于上述内容,因此创建了数据:
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);
Run Code Online (Sandbox Code Playgroud)
以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"}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
组件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);
}
Run Code Online (Sandbox Code Playgroud)
组件模板(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>
Run Code Online (Sandbox Code Playgroud)
请注意,box-component的另一个实例嵌套在顶级box-component中。但是,渲染时,仅渲染顶级box的内容,而不渲染嵌套在其中的box中的内容。
看起来像这样:
顶层盒2-1
级
这是项目2-2
级
这是项目
内部盒子
这是一个盒子
这是一个项目
有没有一种方法可以实现递归嵌套渲染?
小智 5
模板使用的任何指令都必须在指令列表中声明。如果它想递归地使用它自己,这包括它自己。因此,在您的情况下,@Component 注释应该是:
@Component(
selector: 'box-component',
templateUrl: 'box_component.html',
directives: const[CORE_DIRECTIVES, BoxComponent]
)
class BoxComponent
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
117 次 |
| 最近记录: |