递归使用Component

问题描述 投票:4回答:1

我正在尝试使用一个组件,其模板引用其中相同组件的另一个实例。

模型是这样的:

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>

请注意,box-component的另一个实例嵌套在顶层box-component中。但是,渲染时,只渲染顶层框的内容,而不是嵌套在其中的框中包含的内容。

它看起来像这样:

顶盒 2 - 1级 这是一个项目 2 - 2级 这是一个项目 内盒 这是一个盒子 这是一个项目

有没有办法实现递归嵌套渲染?

dart angular-dart
1个回答
3
投票

必须在指令列表中声明模板使用的任何指令。如果它想要递归地使用它自己,这包括它自己。所以在你的情况下@Component注释应该是:

@Component(
    selector: 'box-component',
    templateUrl: 'box_component.html',
    directives: const[CORE_DIRECTIVES, BoxComponent]
)
class BoxComponent
© www.soinside.com 2019 - 2024. All rights reserved.