代码之家  ›  专栏  ›  技术社区  ›  mohammad rostami siahgeli

为什么ng模板在Angular中不起作用?

  •  0
  • mohammad rostami siahgeli  · 技术社区  · 8 年前

    我们不能使用 *ngFor *ngIf 在同一个元素上。一种方法是将它们筑巢。几乎在任何地方都可以,除了在桌子上,当我们都想循环时 tr 并有条件地打印它们。

    suggested here 我们应该使用 <template> <ng-template> 元素,这样它就不会被打印到DOM中。

    但我不能让它工作。它只是不打印任何内容。 Here's a plunker to show it in action .

    我该怎么办?

    3 回复  |  直到 8 年前
        1
  •  9
  •   super cool    8 年前

    由于*ngIf呈现为[ngIf],请尝试直接在模板上使用[ngIf],它应该可以工作。

    当我们在指令前面加*时,我们告诉它使用 元素作为模板附加到它。基本上,ngIf是 ng模板+[ng If]。

    Html:

    <tr *ngFor="let item of items">
       <ng-template [ngIf]="item.month == 12">
            <td>{{ item.year }}</td>
            <td>{{ item.month }}</td>
       </ng-template>
    </tr>
    

    或者干脆用*ngIf来装饰

    <tr *ngFor="let item of items">
       <div ngIf*="item.month == 12">
            <td>{{ item.year }}</td>
            <td>{{ item.month }}</td>
       </div>
    </tr>
    

    更新 plunker

    article 论结构指令

        2
  •  8
  •   Hrishikesh Kale    7 年前

    所以有一个叫做 ng容器 而且

    ng容器和ng模板目前都是(2.x,4.x) 用于在不引入其他元素的情况下将元素组合在一起 将在页面上呈现的元素(例如div或span)。

    ng模板和ng容器之间的区别是

    ng模板用于结构指令,如ng if、ng for和ng switch。如果在没有structural指令的情况下使用它,则不会发生任何事情并进行渲染。

    ng容器在没有合适的包装器或父容器时使用。在大多数情况下,我们使用div或span作为容器,但在这种情况下,当您想要使用多个结构指令,但不能在一个元素上使用多个结构指令时,在这种情况下,可以使用ng container作为容器

    就你而言

    <ng-template> 用于声明模板。这里需要隐藏/显示一些节点

    所以你需要使用ng容器

    <tr *ngFor="let item of items">
        <ng-container *ngIf="item.month == 12">
            <td>{{ item.year }}</td>
            <td>{{ item.month }}</td>
        </ng-container>
    </tr>
    

    这里有几个链接可以帮助你理解两者

    相关的 link

    structural directives

    discussion ng模板与ng容器

        3
  •  1
  •   Tadele Ayelegn    8 年前

    以下是在使用ng模板替换else用例时,如何使其工作 *ngIF

    <p *ngIf="a > b; else notTrue"> A Is Greater Than B <p>
    <ng-template #notTrue>
      <> B Is Greater Than A <p>
    </ng-template>
    

    在第一段标记中创建一个名为 notTrue 并在室内使用 ng模板 标记以打印段落中的行,如果 a < b ,

        4
  •  1
  •   vijayakumarpsg587    6 年前

    我希望你现在已经找到了答案。这是为那些还没有找到答案的人准备的。 更好地解释 ng-template angular与结构指令(*ngIf,*ngSwitch)一起使用的模板元素,该指令被编译以生成其中的结构。将上述结构指令与ng模板一起使用的问题是,当*ngIf为true时,将生成一个模板。但是我们没有指定应该呈现这个模板。另一种方法是使用*ngIf作为[ngIf]属性绑定值,其中属性绑定本身应该是布尔值。

    现在angular将其解释为模板应该在布尔值为真时生成和呈现。下面提供了一个非常基本的例子。

    (我无法使用pluker链接。这是我的stackblitz。) link

    希望这有帮助。这方面有一篇很棒的文章 ng-template

    推荐文章