如何在没有ngFor和另一个@Component的情况下多次重复一段HTML [英] How to repeat a piece of HTML multiple times without ngFor and without another @Component
问题描述
问题很简单,我想在模板中多次重复一段HTML.
The problem is simple, I want to repeat a piece of HTML, multiple times in my template.
但是我希望在页面的不同位置重复此操作,这意味着ngFor并不是解决方案,因为这些片段会直接一个接一个地重复.
But I want it to be repeated at different places in my page, this means that a ngFor is not the solution as the pieces would be repeated directly one after the other.
一个可行的解决方案"是为我重复的HTML定义一个特定的@Component,并执行类似的操作:
<p>Whatever html</p><my-repeated-html></my-repeated-html><h4>Whatever</h4><my-repeated-html></my-repeated-html>
A 'working solution' would be to define a specific @Component for my repeated HTML, and do something like that :
<p>Whatever html</p><my-repeated-html></my-repeated-html><h4>Whatever</h4><my-repeated-html></my-repeated-html>
但是我发现创建一个专门的组件来完成类似的事情是过分的,它没有任何功能性意义,并且只在我要设置的html结构中需要.
But I find it overkill to create a dedicated component for doing something like that, it as no functional meaning and is only required by the html structure I want to setup.
ng2模板引擎中是否真的没有任何东西可以定义内部模板"并在当前模板中的任何需要的地方使用它?
如果答案为否,我想我宁愿复制HTML,即使那有点糟.
If the answer is no I guess I would rather duplicate the HTML, even if that kinda sucks.
推荐答案
更新Angular 5
ngOutletContext
重命名为ngTemplateOutletContext
另请参见 https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29
原始
最近添加的 ngTemplateOutlet 可能是你想要什么
The recently added ngTemplateOutlet might be what you want
<template [ngTemplateOutlet]="templateRefExpression" [ngOutletContext]="objectExpression"></template>
目前可以像
<template #templateRef>
<pre>{{self | json }}</pre>
</template>
<template [ngTemplateOutlet]="templateRef"></template>
模板也可以传递到子组件以在其中进行渲染
A template can also be passed to a child component to be rendered there
@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;
}
使用方式
<some-child>
<template>
<pre>{{self | json }}</pre>
</template>
</some-child>
另一个> 柱塞示例
使用以
Another Plunker example
that uses data passed as
<template [ngTemplateOutlet]="..." [ngOutletContext]="templateData"
这样ngOutletContext
可以在模板中使用
<template let-image="image">
{{image}}
其中image
是templateData
如果使用$implicit
<template [ngTemplateOutlet]="..." [ngOutletContext]="{$implicit: templateData}"
ngOutletContext
可以在模板中使用
<template let-item>
{{item}}
这篇关于如何在没有ngFor和另一个@Component的情况下多次重复一段HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!