开发学院

您的位置:首页>教程>正文

教程正文

Angular 4 指令

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.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类包含在上述文件的声明中。该类也从下面给出的文件中导入。
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类型的元素,这是必需的。元素具有应用更改文本指令的所有细节。

  我们已经添加了console.log元素,输出可以在浏览器控制台中看到,同时元素的文本也如上所示进行了更改。

  现在,浏览器将显示以下内容。

change_text_directive.jpg