Angular4-directives
Angular 4-ディレクティブ
Angularの Directives は 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.ts および change-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* クラスは、上記のファイルの宣言に含まれています。 クラスは、以下のファイルからもインポートされます。
テキストを変更します。 指令
import { Directive } from '@angular/core';
@Directive({
selector: '[changeText]'
})
export class ChangeTextDirective {
constructor() { }
}
上記のファイルにはディレクティブがあり、セレクタープロパティもあります。 セレクターで定義するものは何でも、ビューで一致する必要があり、カスタムディレクティブを割り当てます。
*app.componentl* ビューで、次のようにディレクティブを追加しましょう-
<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* 要素を追加しました。 同じの出力は、ブラウザコンソールで確認できます。 要素のテキストも上記のように変更されます。
これで、ブラウザには次のように表示されます。