Angular 4 - 指令



指令在 Angular 中是一個js類,宣告為@directive。Angular 中有 3 種指令。這些指令列在下面:

元件指令

這些形成了主要類,其中包含有關如何在執行時處理、例項化和使用元件的詳細資訊。

結構指令

結構指令基本上處理操作 DOM 元素。結構指令在指令前有一個 * 號。例如,*ngIf*ngFor

屬性指令

屬性指令用於更改 DOM 元素的外觀和行為。您可以建立自己的指令,如下所示。

如何建立自定義指令?

在本節中,我們將討論將在元件中使用的自定義指令。自定義指令由我們建立,不是標準的。

讓我們看看如何建立自定義指令。我們將使用命令列建立指令。使用命令列建立指令的命令為:

ng g directive nameofthedirective

e.g

ng g directive changeText

這在命令列中顯示如下

C:\projectA4\Angular 4-app>ng g directive changeText
installing directive
   create src\app\change-text.directive.spec.ts
   create src\app\change-text.directive.ts
   update src\app\app.module.ts

以上檔案,即change-text.directive.spec.tschange-text.directive.ts被建立,並且app.module.ts檔案被更新。

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';

@NgModule({
   declarations: [
      AppComponent,
      NewCmpComponent,
      ChangeTextDirective
   ],

   imports: [
      BrowserModule
   ],

   providers: [],
   bootstrap: [AppComponent]
})

export class AppModule { }

ChangeTextDirective類包含在上面檔案中的宣告中。該類也從下面給出的檔案中匯入。

change-text. directive

import { Directive } from '@angular/core';
@Directive({
   selector: '[changeText]'
})

export class ChangeTextDirective {
   constructor() { }
}

以上檔案包含一個指令,並且它還有一個選擇器屬性。我們在選擇器中定義的內容必須與我們在檢視中分配自定義指令的位置匹配。

app.component.html檢視中,讓我們新增指令如下:

<div style="text-align:center">
   <span changeText >Welcome to {{title}}.</span>
</div>

我們將對change-text.directive.ts檔案進行如下更改:

change-text.directive.ts

import { Directive, ElementRef} from '@angular/core';
@Directive({
   selector: '[changeText]'
})

export class ChangeTextDirective {
   constructor(Element: ElementRef) {
      console.log(Element);
      Element.nativeElement.innerText="Text is changed by changeText Directive. ";
   }
}

在上面的檔案中,有一個名為ChangeTextDirective的類和一個建構函式,它接受型別為ElementRef的元素,這是必需的。該元素包含應用Change Text指令的所有詳細資訊。

我們添加了console.log元素。可以在瀏覽器控制檯中看到相同的結果。元素的文字也如上所示更改。

現在,瀏覽器將顯示以下內容。

ChangeText Directive
廣告