4

I know some of you will cringe with this question because I know that what I'm asking about isn't best practice. However, I'm going to ask anyway and hope to keep the abuse to a minimum.

ngIf removes elements from the DOM when the conditional statement is false. Is there a setting, flag, parameter, etc. that will alter the behavior of ngIf so that the elements stay in the DOM and are set to display: none instead? I'm not looking for a workaround, like [hidden], but I want to know if it is possible to change the behavior of *ngIf.

I was quickly (this is the keyword) updating an existing jQuery project. That project is using ".toggle()" methods for an accordion. As part of the update, the accordion items are now filtered with a ngIf. Because the jQuery code initializes the accordions when the app loads, removing them with ngIf, "uninitialized" them.

I used a workaround to address the issue. But I am still curious as to whether or not the option to change the behavior of ngIf is available.

porgo
  • 1,729
  • 2
  • 17
  • 26
Wayne F. Kaskie
  • 3,257
  • 5
  • 33
  • 43
  • The answer is no. Just use a style or class binding. – JB Nizet May 01 '19 at 14:00
  • 2
    Why don't you use `[hidden]` instead – Ashish Ranjan May 01 '19 at 14:00
  • Did you check the documentation? [ngIf](https://angular.io/api/common/NgIf#description) I think that there is no such option... You should use `[hidden]` for this behavior. – Michal S May 01 '19 at 14:02
  • 3
    Possible duplicate of [What is the equivalent of ngShow and ngHide in Angular 2+?](https://stackoverflow.com/questions/35578083/what-is-the-equivalent-of-ngshow-and-nghide-in-angular-2) – Igor May 01 '19 at 14:15

3 Answers3

4

ngIf doesn't have that kind of behavior.

Try ngStyle instead:

[ngStyle]="{display: condition ? 'block' : 'none'}"
1

You can use [hidden]. Remember to deny your first condition.

<div [hidden]="!yourCondition" >
    
</div>
Miguel Carvalhais Matos
  • 1,113
  • 2
  • 13
  • 21
0

If you where not trying to just change the behavior of ng-if and just trying to get the behavior of what you are talking about you can use

ng-show