ng模板的Blazor等价物
角度组件可以具有其引用的任意数量的子模板。例如,我可以制作一个Foo组件,内联指定一些正文内容,以及其他内容的模板:ng模板的Blazor等价物,blazor,Blazor,角度组件可以具有其引用的任意数量的子模板。例如,我可以制作一个Foo组件,内联指定一些正文内容,以及其他内容的模板: <Foo> This is my body <ng-template #header> This is my header <ng-template> <ng-template #footer> This is my footer <ng-template
<Foo>
This is my body
<ng-template #header>
This is my header
<ng-template>
<ng-template #footer>
This is my footer
<ng-template>
<Foo>
这是我的身体
这是我的头球
这是我的页脚
Foo组件可以将这些模板引用为“ChildContent”,并在其标记中使用它们:
<div>
<h1>
<ng-template [ngTemplateOutlet]="header"></ng-template>
</h1>
<div>
<p>Hi! I'm a Foo. My body content:</p>
<p><ng-content></ng-content></p>
</div>
<h3>
<ng-template [ngTemplateOutlet]="footer"></ng-template>
</h3>
</div>
嗨!我是个傻瓜。我的身体内容:
因此,我的Foo示例用法(上面的第一个代码示例)将呈现在DOM中,如下所示:
<div>
<h1>
This is my header
</h1>
<div>
<p>Hi! I'm a Foo. My body content:</p>
<p>This is my body</p>
</div>
<h3>
This is my footer
</h3>
</div>
这是我的头球
嗨!我是个傻瓜。我的身体内容:
这是我的身体
这是我的页脚
Blazor中的等价物是什么?换句话说,我希望能够定义一个组件Foo,以便它可以在其子内容标记中通过内联方式传递呈现片段。Blazor使用RenderFragment类和属性来生成模板区域 在下面的示例中,我们有页眉、正文和页脚的模板,如您在示例中所述
<div>
<h1>
@HeaderTemplate
</h1>
<div>
<p>Hi! I'm a Foo. My body content:</p>
<p>@ChildContent</p>
</div>
<h3>
@FooterTemplate
</h3>
</div>
@code {
[Parameter]
public RenderFragment HeaderTemplate { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
[Parameter]
public RenderFragment FooterTemplate { get; set; }
}
@头模板
嗨!我是个傻瓜。我的身体内容:
@儿童内容
@页脚模板
@代码{
[参数]
公共呈现片段头模板{get;set;}
[参数]
公共RenderFragment ChildContent{get;set;}
[参数]
公共RenderFragment页脚模板{get;set;}
}
用法:
<Foo>
<HeaderTemplate>
This is my header
</HeaderTemplate>
<ChildContent>
<p>This is my body</p>
</ChildContent>
<FooterTemplate>
This is my footer
</FooterTemplate>
</Foo>
这是我的头球
这是我的身体
这是我的页脚
注意:使用示例中模板的顺序无关紧要
无效用法:
<Foo>
<!-- this will fail, because Blazor cannot determine where the <p> content belongs. -->
<p>This is my body</p>
<HeaderTemplate>
This is my header
</HeaderTemplate>
<FooterTemplate>
This is my footer
</FooterTemplate>
</Foo>
这是我的身体
这是我的头球
这是我的页脚
我在问题中提到了渲染片段:我想“在子内容标记中以内联方式传递渲染片段”。您的示例显示了如何在组件中渲染渲染片段(我已经知道),但没有显示如何在组件的使用点使用子标记填充这些渲染片段(我的第一个示例)。我发现角度模板有点混乱。我会试着看看能不能帮你找到答案。Blazor组件可以有ChildContent,它是一个RenderFragment,按约定命名,或者如示例所示的命名模板。如果不在组件主体中显式放置ChildConent元素,则无法混合这两个元素。但是,这些项不需要特定的顺序,它们将在使用@templateName的位置呈现。