- Angular UI Development with PrimeNG
- Sudheer Jonna Oleg Varaksin
- 349字
- 2021-07-15 17:32:56
Built-in directives
Angular has a lot of built-in directives: ngIf, ngFor, ngSwitch, ngClass, and ngStyle. The first three directives are so called structural directives, which are used to transform the DOM's structure. Structural directives start with an asterisk (*). The last two directives manipulate the CSS classes and styles dynamically. Let's explain the directives in the examples.
The ngIf directive adds and removes elements in the DOM, based on the Boolean result of an expression. In the next code snippet, <h2>ngIf</h2> is removed when the show property evaluates to false and gets recreated otherwise:
<div *ngIf="show">
<h2>ngIf</h2>
</div>
Angular 4 has introduced a new else clause with the reference name for a template defined by ng-template. The content within ng-template is shown when the ngIf condition evaluates to false:
<div *ngIf="showAngular; else showWorld">
Hello Angular
</div>
<ng-template #showWorld>
Hello World
</ng-template>
ngFor outputs a list of elements by iterating over an array. In the next code snippet, we iterate over the people array and store each item in a template variable called person. This variable can be then accessed within the template:
<ui>
<li *ngFor="let person of people">
{{person.name}}
</li>
</ui>
ngSwitch conditionally swaps the contents dependent on condition. In the next code snippet, ngSwitch is bound to the choice property. If ngSwitchCase matches the value of this property, the corresponding HTML element is displayed. If no matching exists, the element associated with ngSwitchDefault is displayed:
<div [ngSwitch]="choice">
<h2 *ngSwitchCase="'one'">One</h3>
<h2 *ngSwitchCase="'two'">Two</h3>
<h2 *ngSwitchDefault>Many</h3>
</div>
ngClass adds and removes CSS classes on an element. The directive should receive an object with class names as keys and expressions as values that evaluate to true or false. If the value is true, the associated class is added to the element. Otherwise, if false, the class is removed from the element:
<div [ngClass]="{selected: isSelected, disabled: isDisabled}">
ngStyle adds and removes inline styles on an element. The directive should receive an object with style names as keys and expressions as values that evaluate to style values. A key can have an optional .<unit> suffix (for example, top.px):
<div [ngStyle]="{'color': 'red', 'font-weight': 'bold', 'border-top': borderTop}">
- Oracle WebLogic Server 12c:First Look
- Practical UX Design
- 算法零基礎一本通(Python版)
- Learning Apache Kafka(Second Edition)
- Hands-On GPU:Accelerated Computer Vision with OpenCV and CUDA
- Java項目實戰精編
- Mastering Unity 2D Game Development(Second Edition)
- Python機器學習:預測分析核心算法
- 一本書講透Java線程:原理與實踐
- Clojure for Machine Learning
- Spring Data JPA從入門到精通
- HTML5與CSS3權威指南
- PostgreSQL 12 High Availability Cookbook
- Microsoft Dynamics GP 2013 Cookbook
- Getting Started with the Lazarus IDE