Difference Between NgIf And Hidden Or Display:none In Angular (angularjswiki.com)
Difference Between NgIf And Hidden Or Display:none In Angular
ngif vs hidden or display:none
The main difference between angular ngIf directive & hidden or display:none is ngIf will add or remove the element from DOM based on condition or expression. hidden
attribute in html5 and display none CSS will show or hide the HTML element.
We will go through the examples to understand them further.
ngIf in Angular
Have a look at a simple ngIf example
<div *ngIf="true">This will be added to DOM by ngIf</div>
<div *ngIf="false">This will be removed from DOM by ngIf</div>
<ng-template *ngIf="true">
<div>This will be added to DOM by ngIf</div>
</ng-template>
<ng-template *ngIf="false">
<div>This will be removed from DOM by ngIf</div>
</ng-template>
hidden or display:none in Angular
Now we will see an example with hidden attribute in html5 and display none CSS.
<p [style.display]="'block'">
This paragraph is visible.
</p>
<p [style.display]="'none'">
This paragraph is hidden but still in the DOM.
</p>
<p hidden>
This paragraph is hidden but still in the DOM.
</p>
Irrespective of display hide or show the paragraph element will be added to the DOM.
Why ngIf directive remove the element rather than hide it?
ngIf vs hidden or display none in Angular
ngIf | hidden or display none |
---|---|
Angular's structural directive | Normal HTML5 attribute |
No DOM element is added if ngIf evaluates to false. | DOM element will be added to HTML |
ngIf might be slow while adding removing elements to the DOM because of intializations | As the element is already added to DOM showing and hiding or very fast |
Ideal for rich angular applications | Ideal if the component is simple no much interaction |
I hope you understand all the differences between ngIf and hidden or display none in Angular
Không có nhận xét nào:
Đăng nhận xét