【问题标题】:unable to remove empty tag using angular 6无法使用 Angular 6 删除空标签
【发布时间】:2018-11-23 08:14:21
【问题描述】:

这里有一个问题,下面是我的 json 数据

 data = {
  "required": false,
  "name": "data",
  "details": [
    {
      "name": "type",
      "details": {
        "visible": false,

      }
    },
    {
      "name": "Creation",
      "details": {

        "visible":true,

      }
    },
    {
      "name": "Creation",
      "details": {

        "visible": false,

      }
    },

    {
      "name": "Modification",
      "details": {

        "visible": true,

      }
    }

  ]
}

.html代码

<ng-container *ngFor="let x of data.details">
  <ul>
  <li *ngIf="x.details.visible">             
      {{x.name}}
  </li>
  </ul>
</ng-container>

这里的问题是,即使我的条件是真的,它正在创建空标签,我的 html 样式受到干扰并出现不需要的空格

在控制台中它向我展示了这样的

<ul _ngcontent-c76=""><!--bindings={
  "ng-reflect-ng-if": "false"
}--></ul>

<ul _ngcontent-c76=""><!--bindings={
  "ng-reflect-ng-if": "true"
}--><li _ngcontent-c76=""> Creation </li></ul>

<ul _ngcontent-c76=""><!--bindings={
  "ng-reflect-ng-if": "false"
}--></ul>

<ul _ngcontent-c76=""><!--bindings={
  "ng-reflect-ng-if": "true"
}--><li _ngcontent-c76=""> Modification</li></ul>

我怎样才能删除那些空白。

以下是我的堆栈闪电战网址。

https://stackblitz.com/edit/angular-yw2zy5

【问题讨论】:

  • 将 *ngIf 移至 ul 标签。
  • ul 中使用ngIf 条件。顺便说一句,你想要这么多uls?还是一个 ul 和多个 lis
  • @AshishRanjan uls & lis 是根据我的数据生成的

标签: javascript angular typescript


【解决方案1】:

您的实施问题:

  1. 您在ul 上拥有*ngFor 而不是li。这会使 ul 在 DOM 上重复出现,从而破坏您的风格。
  2. 您应该将ng-container 用作li 的父代,而不是将其用作ul 的父代。这样,您就可以在li 上添加*ngIf 条件,同时在ng-container 上使用*ngFor

试试这个:

<hello name="{{ name }}"></hello>
<ul>
    <ng-container *ngFor="let x of data.details">
        <li *ngIf="x.details.visible">
            {{x.name}}
        </li>
    </ng-container>
</ul>

这里有一个Sample StackBlitz 供您参考。

【讨论】:

    【解决方案2】:

    您应该将您的模板更改为以下

    <ul>
      <ng-container *ngFor="let x of data.details">
        <li *ngIf="x.details.visible">
          {{x.name}}
        </li>
      </ng-container>
    </ul>
    

    您不希望有一堆 ul 和单个 li 元素。如果满足x.details.visible 条件,上面的代码将创建一个ul 并在其中添加一些li 元素

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      • 1970-01-01
      相关资源
      最近更新 更多