2

I have hit this a couple times, where I want to selectively render a tag on a condition but leave the contents. My use case is a directive when I have an optional link, so I want to render the opening and closing <a> tags but leave the contents alone in either case.

<a ng-if="condition"><p>Render me always</p></a>
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
httpete
  • 2,765
  • 26
  • 34
  • There is no way to tell a browser to conditionally use a closing tag regardless of framework used. You always need to consider the whole element – charlietfl Jan 04 '16 at 15:39

2 Answers2

4

The only way to do it in Angular without writing custom directive is to use two ngIf conditions:

<a ng-if="condition">
    <p>Render me always</p>
</a>

<p ng-if="!condition">Render me always</p>
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • This is the best quick & dirty solution, but as @dfsq alluded to, writing a directive would be, IMO, a better solution – jusopi Jan 04 '16 at 15:41
  • @jusopi I actually don't think this is very good idea to write a directive for this. It's not very common thing to do I think, so much simpler just to go with two ngIf's. Maybe not the most elegant solution but still. – dfsq Jan 04 '16 at 16:00
  • you're right, a directive is rather overkill for his particular usecase. After reading this, I proposed an ng-class solution since this is really a cosmetic issue currently. Of course that could change if it encompasses more than how a link should appear. – jusopi Jan 04 '16 at 16:10
  • What I have done to date, is to have an ng-include – httpete Jan 04 '16 at 16:12
1

Looking at this particular use case, this seems to be more of a cosmetic issue. Would not the ng-class directive not work for this?

<a ng-class="{'non-link':boolCondition}"><p>...contents</p></a>

CSS is responsible for the basic look & feel so create a style that reflects that and then you needn't worry about duplication or directives, etc.

.non-link {
    pointer-events: none;
    cursor: default;
}

ref - Is it possible to make an HTML anchor tag not clickable/linkable using CSS?

Community
  • 1
  • 1
jusopi
  • 6,791
  • 2
  • 33
  • 44