ngIf 仅用于 _this_ 元素,无论如何都显示孩子
ngIf only for _this_ element, show childs anyway
我知道我的问题的措辞可能有点奇怪,但这就是我想要的:
我有一个 div,我想环绕一个 input
,但仅当 divIsNeeded
时。我 总是 想要显示 input
字段。
查看文档,我找不到任何东西。有什么办法吗?
<!-- this should only be there if I actually need it, otherwise I don't want this div -->
<div *ngIf="needsInputGroup" class="input-group">
<!-- this should always be visible -->
<input type="text" placeholder="bla" />
</div>
<div *ngIf="needsInputGroup" class="input-group">
<input type="text" placeholder="bla" />
</div>
<input *ngIf="!needsInputGroup" type="text" placeholder="bla" />
您可以创建一个自定义组件来为您执行此操作并在任何地方重复使用它。我认为没有其他方法。但是自定义组件在内容周围添加了另一个元素
Günter 在 中的建议可行,但您必须指定子项两次。相反,您可以利用 <ng-template>
元素仅指定一次子元素。在这种特定情况下,这不是问题,因为元素相当简单,但如果内容更大怎么办?
<ng-template>
的内容不会在放置的地方呈现,而是有点像轻量级组件的定义。一旦放置在某个地方,它就会渲染,但之前不会。 ng-template
的另一个类比是一个函数:您定义它,但在调用它之前不会得到结果。
所以在我们模板的任何地方,我们都可以定义内部内容。我们给它一个引用 #children
,稍后我们将使用它在其他地方渲染模板。
<ng-template #children>
<input type=text placeholder=bla>
</ng-template>
现在我们根据条件渲染不同的东西。我们通过将其引用(我们给它的名称)传递给结构指令 ngTemplateOutlet
.
来渲染模板
<ng-container *ngIf="needsInputGroup">
<div class="input-group">
<ng-container *ngTemplateOutlet="children"></ng-container>
</div>
</ng-container>
<ng-container *ngIf="!needsInputGroup">
<ng-container *ngTemplateOutlet="children"></ng-container>
</ng-container>
我知道我的问题的措辞可能有点奇怪,但这就是我想要的:
我有一个 div,我想环绕一个 input
,但仅当 divIsNeeded
时。我 总是 想要显示 input
字段。
查看文档,我找不到任何东西。有什么办法吗?
<!-- this should only be there if I actually need it, otherwise I don't want this div -->
<div *ngIf="needsInputGroup" class="input-group">
<!-- this should always be visible -->
<input type="text" placeholder="bla" />
</div>
<div *ngIf="needsInputGroup" class="input-group">
<input type="text" placeholder="bla" />
</div>
<input *ngIf="!needsInputGroup" type="text" placeholder="bla" />
您可以创建一个自定义组件来为您执行此操作并在任何地方重复使用它。我认为没有其他方法。但是自定义组件在内容周围添加了另一个元素
Günter 在 <ng-template>
元素仅指定一次子元素。在这种特定情况下,这不是问题,因为元素相当简单,但如果内容更大怎么办?
<ng-template>
的内容不会在放置的地方呈现,而是有点像轻量级组件的定义。一旦放置在某个地方,它就会渲染,但之前不会。 ng-template
的另一个类比是一个函数:您定义它,但在调用它之前不会得到结果。
所以在我们模板的任何地方,我们都可以定义内部内容。我们给它一个引用 #children
,稍后我们将使用它在其他地方渲染模板。
<ng-template #children>
<input type=text placeholder=bla>
</ng-template>
现在我们根据条件渲染不同的东西。我们通过将其引用(我们给它的名称)传递给结构指令 ngTemplateOutlet
.
<ng-container *ngIf="needsInputGroup">
<div class="input-group">
<ng-container *ngTemplateOutlet="children"></ng-container>
</div>
</ng-container>
<ng-container *ngIf="!needsInputGroup">
<ng-container *ngTemplateOutlet="children"></ng-container>
</ng-container>