为所有 Angular 个可使用 *ngIf 呈现的模板设置 class

Setting class for all Angular templates renderable with *ngIf

我在 DIV 上有一个 class 部分 需要渲染。它按预期工作。

<div *ngIf="decoded; then coordinates"></div>
<ng-template #coordinates>
  <div class="section">...</div>
</ng-template>

我尝试将 class 赋值移动到包含该指令的 DIV。但是,演绎没有效果。

<div *ngIf="decoded; then coordinates" class="section"></div>
<ng-template #coordinates>
  <div>...</div>
</ng-template>

外面的DIV整体消失,取而代之的是模板的内容。这让我很烦恼,因为如果我有多个组件,我不得不在模板中的所有内容周围添加一个额外的 DIV。 (另外,我觉得有点奇怪,我们不保留与 *ngIf 一起使用的标签的任何属性,并且可以使用任意一个,而 。)

<div *ngIf="decoded; then coordinates"></div>
<ng-template #coordinates>
  <div class="section">
    <div>...</div>
    <span>...</span>
    <bzz>...</bzz>
  </div>
</ng-template>

我试图通过在模板上设置 class 来欺骗浏览器,但由于它实际上并没有在 DOM 中呈现,所以它当然失败了。

<div *ngIf="decoded; then coordinates"></div>
<ng-template #coordinates class="section">
  <div...</div>
</ng-template>

有没有办法强制使用条件指令的 DIV 在根据模板内容呈现时保留其 class?

您可以尝试使用 ng-container 并对其应用 *ngIf,在这种情况下它应该会如您所愿

<div class="section">
  <ng-container *ngIf="decoded; then coordinates"></ng-container>
</div>

<ng-template #coordinates>
  <div>...</div>
</ng-template>

TL;DR: Angular 正在按照您的要求进行;您使用 then 告诉它呈现 不同于 指令在 truth-y 情况下所在的元素。如果这不是您想要的行为,请不要那样做。


*ngIf*ngFor 这样的结构指令实际上是一个被扩展的 shorthand(这曾经被称为 “脱糖”), 看https://angular.io/guide/structural-directives or more specifically https://angular.io/api/common/NgIf#description中的例子:

Simple form with shorthand syntax:

<div *ngIf="condition">Content to render when condition is true.</div>

Simple form with expanded syntax:

<ng-template [ngIf]="condition">
    <div>Content to render when condition is true.</div>
</ng-template>

请注意,对于条件渲染,所有内容都包含在 ng-template 中。


如果你的模板是这样写的:

<div *ngIf="decoded" class="section">...</div>

它将扩展为:

<ng-template [ngIf]="decoded">
  <div class="section">...</div>
</ng-template>

实际呈现的是:

<div class="section">...</div>

请注意,class 仍然包含在内,与您在其他结构指令中遇到的情况一致。


但是,当您使用 then 时,shorthand:

<div *ngIf="decoded; then coordinates" class="section"></div>
<ng-template #coordinates>
  <div>...</div>
</ng-template>

扩展为:

<ng-template [ngIf]="decoded" [ngIfThen]="coordinates">
  <div class="section"></div>
</ng-template>
<ng-template #coordinates>
  <div>...</div>
</ng-template>

第一个 ng-template 的内容现在已无关紧要,因为这两种情况都不是呈现的内容。它要么呈现 #coordinates 模板内容,要么什么都不呈现,所以你得到:

<div>...</div>

而你的 class 似乎已经消失了。但这就是你要求的; then 的要点是 渲染 *ngIf 所在的元素,在 truth-y 的情况下,而是渲染其他东西。


有关这些基础 ng- 元素的更多信息,我在我的博客上写道 Angular's "ng-" elements

我建议看看这篇很棒的文章Everything you need to know about ng-template, ng-content, ng-container, and *ngTemplateOutlet in Angula

它包含您需要了解的有关 Angular 的结构指令的所有信息,并提供了很好的解释和示例。