问题很简单,我想在我的模板中多次重复一段HTML.
但是我希望它在我的页面中的不同位置重复,这意味着ngFor不是解决方案,因为这些片段会一个接一个地直接重复.
一个"工作解决方案"是为我重复的HTML定义一个特定的@Component,并执行类似的操作:
<p>Whatever html</p><my-repeated-html></my-repeated-html><h4>Whatever</h4><my-repeated-html></my-repeated-html>
但是我觉得创建一个专用组件来做类似的事情有点过分,它没有任何功能意义,只有我想设置的html结构才需要.
在ng2模板引擎中是否真的没有允许定义"内部模板"并在当前模板中的任何需要的地方使用它?
如果答案是否定的,我想我宁愿复制HTML,即使有点糟糕.
Gün*_*uer 30
更新Angular 5
ngOutletContext 被重命名为 ngTemplateOutletContext
另见https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29
原版的
最近添加的ngTemplateOutlet可能就是您想要的
<template [ngTemplateOutlet]="templateRefExpression" [ngOutletContext]="objectExpression"></template>
Run Code Online (Sandbox Code Playgroud)
它目前可以像
<template #templateRef>
<pre>{{self | json }}</pre>
</template>
<template [ngTemplateOutlet]="templateRef"></template>
Run Code Online (Sandbox Code Playgroud)
模板也可以传递给子组件以在那里呈现
@Component({
selector: 'some-child',
providers: [],
template: `
<div>
<h2>Child</h2>
<template [ngTemplateOutlet]="template" ></template>
<template [ngTemplateOutlet]="template" ></template>
</div>
`,
directives: []
})
export class Child {
@ContentChild(TemplateRef) template:TemplateRef;
}
Run Code Online (Sandbox Code Playgroud)
用得像
<some-child>
<template>
<pre>{{self | json }}</pre>
</template>
</some-child>
Run Code Online (Sandbox Code Playgroud)
另一个
使用传递的数据的Plunker示例
<template [ngTemplateOutlet]="..." [ngOutletContext]="templateData"
Run Code Online (Sandbox Code Playgroud)
这种方式ngOutletContext可以在模板中使用
<template let-image="image">
{{image}}
Run Code Online (Sandbox Code Playgroud)
哪个image属性templateData
如果$implicit使用
<template [ngTemplateOutlet]="..." [ngOutletContext]="{$implicit: templateData}"
Run Code Online (Sandbox Code Playgroud)
在ngOutletContext可以在模板中使用象
<template let-item>
{{item}}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8757 次 |
| 最近记录: |