我有这样一个嵌套的ng-template结构。
@Component({
selector: 'my-app',
template: `
<list>
<ng-template *ngFor="let item of Items" #ListItem>
<ng-template #ListItemLine>{{ item[0] }}</ng-template>
<ng-template #ListItemLine>{{ item[1] }}</ng-template>
<ng-template #ListItemLine>{{ item[2] }}</ng-template>
I can see this line, but can't get above templates
</ng-template>
</list>
`,
})
export class App {
Items: Array<Array<string>> = [
[ "1-1", "1-2", "1-3", ],
[ "2-1", "2-2", "2-3", ],
[ "3-1", "3-2", "3-3", ],
[ "4-1", "4-2", "4-3", ],
[ "5-1", "5-2", "5-3", ],
]
}如何在组件中呈现子ng-component:
@Component({
selector: 'list',
template: `
<ul>
<li *ngFor="let item of Items">
<ng-container *ngTemplateOutlet="item"></ng-container>
</li>
</ul>
`,
})
export class ListComponent {
@ContentChildren('ListItem') public Items;
}Plunkr https://plnkr.co/edit/Hi1ZqPAAYyIbclUuzRrl?p=preview
提前谢谢你。
更新
最后,我想把有角度的材料组件包装到我的组件中,所以如果我要找到一个比材料更糟糕的UI,我就不需要在我的程序中更改材料组件的所有精度,我只需要更改包装器UI组件的实现。
对于示例,让我们尝试包装mat-list组件。我需要为mat-list容器做一个包装器,让我们称之为my-list
@Component({
selector: 'my-list',
template: `
<mat-list>
<ng-content></ng-content>
</mat-list>
`,
})以及mat-list-item的包装器
@Component({
selector: 'my-list-item',
template: `
<mat-list-item>
<ng-content></ng-content>
</mat-list>
`,
})HTML呈现结果是:
- ...
每个材料组件都被我的包装所包围,所以随材料而来的指令和样式将无法工作。
发布于 2017-11-21 00:33:38
下面是我如何根据你提供的信息来解决这个问题。正如您已经指出的,我已经制作了两个组件list和list-item。列表组件基于输入数组呈现list-item组件,列表组件的内容必须包含定义列表项模板的模板。样本代码:
@Component({
selector: 'list',
template: `
<ul>
<list-item *ngFor="let item of items" [data]="item" [itemTemplate]="itemTemplate"></list-item>
<ng-content></ng-content>
</ul>
`,
})
export class ListComponent {
@ContentChild(TemplateRef)
public itemTemplate: TemplateRef;
@Input()
public items: any[];
}然后,list-item组件只呈现容器元素中提供的列表项模板。样本代码:
@Component({
selector: 'list-item',
template: `
<li>
<ng-container *ngTemplateOutlet="itemTemplate; itemContext"></ng-container>
</li>
`,
})
export class ListItemComponent {
@Input()
public data: any;
@Input()
public itemTemplate: Template;
public get itemContext(): any {
return { $implicit: data };
}
}然后,您可以以不同的方式使用它。我做了一个例子,只是一个简单的列表,而另一个例子,项目模板又是一个列表,所以您可以从树中得到一个列表。样本代码:
@Component({
selector: 'my-app',
template: `
<list [items]="Items">
<ng-template let-items>{{ items | json }}</ng-template>
</list>
<list [items]="Items">
<ng-template let-items>
<list [items]="items">
<ng-template let-items>{{ items | json }}</ng-template>
</list>
</ng-template>
</list>
`,
})
export class App {
Items: Array<Array<string>> = [
[ "1-1", "1-2", "1-3", ],
[ "2-1", "2-2", "2-3", ],
[ "3-1", "3-2", "3-3", ],
[ "4-1", "4-2", "4-3", ],
[ "5-1", "5-2", "5-3", ],
]
}我还用代码制作了一个柱塞示例,您可以在其中运行它。柱塞试样
https://stackoverflow.com/questions/47401326
复制相似问题