是否可以通过角度2有条件地关闭html标签?

时间:2017-03-24 14:31:31

标签: html angular

我需要这样的东西:

<tr>
  somecode...
</tr *ngIf="some condition">

当然不支持,但有没有办法实现这种行为?

我有一个表,我希望使用接收节点列表(List)的组件递归地添加行,迭代节点,打印它们并为每个节点的每个子节点调用自己,大致如下:

main.component.html

<table class="table table-bordered">
    <thead>
    <tr>
        <th>node names</th>
    </tr>
    </thead>
    <tbody>
        <tr app-rower [nodes]="nodes"></tr>
    </tbody>
</table>

rower.component.html:

<ng-container *ngFor="let node of tree">
    <tr>
        <td>
            {{node.name}}
        </td>
    </tr *ngIf="node.hasChildren">
    <tr *ngIf="node.hasChildren" app-rower [tree]="node.children" >
    </tr *ngIf="!node.hasChildren">
</ng-container>

所以最终的HTML会是:

<table>
    <thead>
        <tr>
            <th>node's names</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>node 1</td>
        </tr>
        <tr>
            <td>node 1's child</td>
        </tr>
        <tr>
            <td>node 1's grandchild</td>
        </tr>
        <tr>
            <td>node 2</td>
        </tr>
        <tr>
            <td>node 2's child</td>
        </tr>
    </tbody>
</table>

1 个答案:

答案 0 :(得分:5)

不,不支持。模板需要是有效的HTML,否则Angular不会解析它。

<ng-container *ngFor="let node of tree">
    <tr>
        <td>
            {{node.name}}
        </td>
    </tr>
    <tr *ngIf="node.hasChildren" app-rower [tree]="node.children" >
    </tr>
</ng-container>