想象一下列表1和列表2:两个列表都包含相同的 <html>
<head></head>
<body>
<div id="pie"></div>
<button id="addData"> Add Data </button>
<script src="http://d3js.org/d3.v4.min.js" charset="utf-8"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" crossorigin="anonymous"></script>
<script src="https://raw.githubusercontent.com/benkeen/d3pie/0.2.1/d3pie/d3pie.min.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var data = [
{ label: "1", value: 1 },
{ label: "2", value: 4 },
{ label: "3", value: 3 }
];
var pie = new d3pie("pie", {
data: {
content: data
}
});
</script>
</body>
</html>
组件:
app-item-card
我如何两次包含该组件,不重复所有输入,输出,类等??
我知道我可以为此目的制作另一个名为@Component({
selector: 'app-example',
template: `
<!-- list 1: items -->
<div *ngFor="let item of (items$ | async)">
<app-item-card (item)="item"
[isSelected]="item.selected"
[selectedClass]="'is-selected'"
(selected)="select(item)"></app-item-card>
</div>
<!-- list 2: favorite items -->
<div *ngFor="let item of (items$ | async)">
<!-- same component app-item-card -->
</div>
`,
})
export class ExampleComponent() {
items$: Observable<Item[]>;
}
的组件,但是我想知道是否有一种方法可以做到这一点。
答案 0 :(得分:1)
您可以将列表逻辑放在<ng-template>
内,进行引用,然后使用*ngTemplateOutlet
指令将其呈现,如下所示:
@Component({
selector: 'app-example',
template: `
<ng-template #listRef>
<div *ngFor="let item of (items$ | async)">
<app-item-card (item)="item"
[isSelected]="item.selected"
[selectedClass]="'is-selected'"
(selected)="select(item)"></app-item-card>
</div>
</ng-template>
<!-- list 1: items -->
<ng-container *ngTemplateOutlet="listRef"></ng-container>
<!-- list 2: favorite items -->
<ng-container *ngTemplateOutlet="listRef"></ng-container>
`,
})
export class ExampleComponent() {
items$: Observable<Item[]>;
}
您还可以按以下方式向模板提供上下文(在您的情况下为items$
:
@Component({
selector: 'app-example',
template: `
<ng-template #listRef let-items$="items$">
<div *ngFor="let item of (items$ | async)">
<app-item-card (item)="item"
[isSelected]="item.selected"
[selectedClass]="'is-selected'"
(selected)="select(item)"></app-item-card>
</div>
</ng-template>
<!-- list 1: items -->
<ng-container *ngTemplateOutlet="listRef; context: ctx"></ng-container>
<!-- list 2: favorite items -->
<ng-container *ngTemplateOutlet="listRef; context: ctx"></ng-container>
`,
})
export class ExampleComponent() {
ctx: any;
items$: Observable<Item[]>;
ngOnInit() {
this.ctx = {
items$: this.items$
};
}
}
另请参阅NgTemplateOutlet
指令官方docs。