- 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}">
- JavaScript前端開發模塊化教程
- 深入理解Bootstrap
- Mastering Adobe Captivate 2017(Fourth Edition)
- Unity Virtual Reality Projects
- Android底層接口與驅動開發技術詳解
- Microsoft Azure Storage Essentials
- C++從入門到精通(第5版)
- C#程序設計(項目教學版)
- INSTANT JQuery Flot Visual Data Analysis
- 游戲設計的底層邏輯
- 軟件開發中的決策:權衡與取舍
- HTML5 and CSS3:Building Responsive Websites
- 計算機應用基礎
- 深入理解MySQL主從原理
- Spring MVC Cookbook