Angular7-directives

提供:Dev Guides
移動先:案内検索

Angular7-ディレクティブ

Angularのディレクティブは、@ directiveとして宣言されているjsクラスです。 Angularには3つのディレクティブがあります。 ディレクティブは以下のとおりです-

コンポーネント指令

これらは、実行時にコンポーネントを処理、インスタンス化、および使用する方法の詳細を含むメインクラスを形成します。

構造指令

構造ディレクティブは、基本的にdom要素の操作を扱います。 構造ディレクティブには、ディレクティブの前に*記号があります。 たとえば、* ngIf および* ngFor

属性ディレクティブ

属性ディレクティブは、dom要素の外観と動作の変更を処理します。 以下のセクションで説明するように、独自のディレクティブを作成できます。

カスタムディレクティブを作成する方法は?

このセクションでは、コンポーネントで使用されるカスタムディレクティブについて説明します。 カスタムディレクティブは当社が作成したもので、標準ではありません。

カスタムディレクティブの作成方法を見てみましょう。 コマンドラインを使用してディレクティブを作成します。 コマンドラインを使用してディレクティブを作成するコマンドは次のとおりです-

ng g directive nameofthedirective
e.g
ng g directive changeText

以下のコードで与えられるように、コマンドラインに表示されます-

C:\projectA7\angular7-app>ng g directive changeText
CREATE src/app/change-text.directive.spec.ts (241 bytes)
CREATE src/app/change-text.directive.ts (149 bytes)
UPDATE src/app/app.module.ts (565 bytes)

上記のファイル、つまり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 { AppRoutingModule } from './app-routing.module';
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,
      AppRoutingModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }
*ChangeTextDirective* クラスは、上記のファイルの宣言に含まれています。 クラスは、以下に示すファイルからもインポートされます-
*change-text.directive*
import { Directive } from '@angular/core';

@Directive({
   selector: '[changeText]'
})
export class ChangeTextDirective {
   constructor() { }
}

上記のファイルにはディレクティブがあり、セレクタープロパティもあります。 セレクターで定義するものは何でも、ビューで一致する必要があり、カスタムディレクティブを割り当てます。

app.componentlビューで、次のようにディレクティブを追加します-

<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
   <h1> Welcome to {{title}}. </h1>
</div>
<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 ディレクティブをspanタグに追加したため、span要素の詳細が表示されます。