为什么ng-template在Angular中不起作用? [英] Why ng-template is not working in Angular?

查看:77
本文介绍了为什么ng-template在Angular中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们不能在同一元素上使用 * ngFor * ngIf .一种技术是嵌套它们.几乎所有地方都可以,除了在表中希望同时遍历 tr 并有条件地打印它们的情况之外.

We can't use *ngFor and *ngIf on the same element. A technique is to nest them. Almost everywhere it's OK, except in tables when we want to both loop over tr and print them conditionally.

此处建议,我们应该使用<代码><模板> ,或 < ng-template> 元素,这样就不会将其打印到DOM.

As suggested here we should use <template>, or <ng-template> elements, so that it won't be printed to the DOM.

但是我无法使其正常工作.它根本不打印任何内容.这里是一个显示它实际效果的工具a>.

But I can't make it work. It simply doesn't print out anything. Here's a plunker to show it in action.

我该怎么办?

推荐答案

由于* ngIf呈现为[ngIf],请尝试在可正常使用的模板上直接使用[ngIf].

As *ngIf is rendered as [ngIf], try using [ngIf] directly on template it should work.

当我们在指令前加*时,就是在告诉它使用元素作为模板附加到该元素.基本上* ngIf是的组合ng-template + [ng-If].

When we prepend a directive with * we are telling it to use the element it’s attached to as the template. Basically *ngIf is a combo of ng-template + [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

or simply you can decorate with *ngIf

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

更新了 朋克车

updated plunker

有用的 文章 关于结构指令

Useful article on Structural directives

这篇关于为什么ng-template在Angular中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆