- Expert Angular
- Mathieu Nayrolles Rajesh Gunasundaram Sridhar Rao
- 303字
- 2021-07-15 17:05:29
Directives
A directive is instructions or guidelines for rendering a template. A class decorated with @Directive to attached metadata is called a directive. There are three types of directive supported by Angular, namely Component Directive, Structural Directive, and Attribute Directive:

A component is one form of a directive with a template that is decorated with @Component: it is actually an extended @Directive with a template feature:
<book-detail></book-detail>
Structural Directives manipulate the DOM elements and alter their structure by adding, removing, and replacing DOM elements. The following code snippet uses two Structural Directives:
<ul> <li *ngFor="let book of books"> {{book.title}} </li> </ul>
Here, the div element has a *ngFor directive that iterates through the books collection object and replaces the title of each book.
An Attribute Directive helps to update the behavior or the appearance of an element. Let's use the Attribute Directive to set the font size of a paragraph. The following code snippet shows an HTML statement implemented with an Attribute Directive:
<p [myFontsize]>Fontsize is sixteen</p>
We need to implement a class annotated with @Directive along with the selector for the directive. This class should be implemented with the instructions on the behavior of the directive:
import { Directive, ElementRef, Input } from '@angular/core'; @Directive({ selector: '[myFontsize]' }) export class FontsizeDirective { constructor(el: ElementRef) { el.nativeElement.style.fontSize = 16; } }
Here, Angular will look for elements with the [myFontsize] directive and sets the font size to 16.
It is necessary to pass the myFontSize directive to the declarations metadata of @NgModule as follows:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { FontsizeDirective } from './fontsize.directive'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent, FontsizeDirective ], bootstrap: [ AppComponent ] }) export class AppModule { }
We will discuss directives in detail in Chapter 6, Creating Directives and Implementing Change Detection.
- Java多線程編程實戰指南:設計模式篇(第2版)
- arc42 by Example
- Java程序設計案例教程
- R用戶Python學習指南:數據科學方法
- 智能搜索和推薦系統:原理、算法與應用
- Access 2010中文版項目教程
- Modernizing Legacy Applications in PHP
- jQuery Mobile Web Development Essentials(Second Edition)
- Visual C++程序設計全程指南
- PHP 7 Programming Blueprints
- LabVIEW數據采集(第2版)
- Spring Microservices
- Mathematica Data Visualization
- JSP程序設計與案例教程
- 軟件定義存儲:原理、實踐與生態