首页 > 解决方案 > Trying to provide hyperlink in HTML based on ng-if condition...not working

问题描述

I want to provide a link on a text based condtion utilizing ng-if. If functions return true I want to provide the link, otherwise display just the value with no link.

<th style="text-align:left">
<span ng-if="(mandalLink())">
<a ng-href="/#!/l2-mandal/{{department}}/{{d}}" title="Click to see data at Mandal Level">{{d}}</a>
</span>
<span ng-if="(!mandalLink())"> {{d}} </span>
</th>

I have used ng-if at other places and its working but in this case it's not. What am I doing wrong here?

标签: angular-ng-if

解决方案


在您的 .html 文件中尝试:

<th style="text-align:left">
  <span ng-if="showLink">
    <a ng-href="/#!/l2-mandal/{{department}}/{{d}}" title="Click to see data at Mandal Level">{{d}}</a>
  </span>
  <span ng-if="!showLink"> {{d}} </span>
</th>

在您的 .ts 文件中(在 ngOnInit 或您获取/分配值到“部门”的位置..)

showLink;

getDepartmentOrWhatEver(){
    ... // your logic getting 'department' assigned
   if (department == "") {
      this.showLink= false;
   }
   else {
      this.showLink= true;
   }
}

来自 ng-if 的文档:

ngIf 指令基于 {expression} 删除或重新创建 DOM 树的一部分。如果分配给 ngIf 的表达式的计算结果为 false 值,则从 DOM 中删除该元素,否则将该元素的克隆重新插入 DOM。

ngIf 与 ngShow 和 ngHide 的不同之处在于 ngIf 完全删除并重新创建 DOM 中的元素,而不是通过 display css 属性更改其可见性。这种差异显着的常见情况是使用依赖于 DOM 中元素位置的 css 选择器,例如 :first-child 或 :last-child 伪类。

仅供参考:函数周围不需要括号,就<span ng-if="mandalLink()">可以了..


推荐阅读