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

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.

主站蜘蛛池模板: 来宾市| 山西省| 横峰县| 永吉县| 拜泉县| 大洼县| 历史| 类乌齐县| 澄城县| 两当县| 延安市| 南城县| 五台县| 方城县| 安塞县| 和林格尔县| 台安县| 黔西| 确山县| 祥云县| 长岭县| 重庆市| 喀喇沁旗| 宣恩县| 宁陕县| 深泽县| 灌南县| 广水市| 康马县| 博野县| 繁昌县| 南昌市| 洛扎县| 车险| 望奎县| 远安县| 綦江县| 合作市| 东乡| 论坛| 随州市|