官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 化隆| 宣汉县| 城固县| 衡水市| 吉隆县| 商河县| 凌海市| 海原县| 临高县| 镶黄旗| 崇州市| 上虞市| 津市市| 南木林县| 宣城市| 贵港市| 华蓥市| 阿图什市| 垣曲县| 微博| 莱阳市| 皋兰县| 方山县| 勃利县| 嘉善县| 天峨县| 津市市| 宜兴市| 鄂托克旗| 玉龙| 玉树县| 博罗县| 新密市| 洪湖市| 怀仁县| 翁源县| 桃园市| 茌平县| 武川县| 德格县| 苏州市|