In AngularJS 1, if you want to toggle the display state of DOM elements, you will probably use the built-in commands in AngularJS 1, such as ng-show or ng-hide:
AngularJS 1 example:
In angular2, the new template syntax allows you to bind expressions to any native properties of DOM elements. This absolutely awesome feature opens up endless possibilities. One of them is to bind the expression to the native hidden property, which is a bit like ng-show, and also sets display: none for the element:
[hidden] example of angular2 (not recommended):
At first glance, the above example seems to be ng-show in AngularJS 1. In fact, they have! important differences.
Both ng-show and ng-hide control the display state of DOM elements through a CSS class called ng-hide, which simply sets the element to display: none. The key here is that AngularJS 1 has been added to the ng-hide class! important, which adjusts the priority of the class so that it can override the assignment of the element's display attribute from other styles.
Back to this example, the display: none style on the native hidden attribute is implemented by the browser. Most browsers don't use it! important to adjust its priority. Therefore, controlling the display state of an element by using [hidden]="expression" can easily be accidentally overwritten by other styles. For example: if I write such a style for this element elsewhere, display: flex, this takes precedence over the native hidden property (see here).
For this reason, we usually use *ngIf to toggle the element presence state to accomplish the same goal:
*ngIf example of angular2 (recommended):
Unlike the native hidden property, *ngIf in angular2 is not style-constrained. No matter what kind of CSS you write, she's safe. However, it is still necessary to mention that *ngIf does not control the display state of the element, but directly achieves the effect of displaying or not by adding/removing the element from the template.
Of course, you can also add a hidden priority to the hidden attribute of an element by using a global style, such as display: none !important, to achieve this effect. You may ask, since the angular group knows these problems, why not just add a global highest priority hidden style to the hidden in the framework? The answer is that we can't guarantee that adding global styles is the best choice for all applications. Because this approach actually breaks the functionality that relies on native hidden capabilities, we leave the choice to the engineers.
|