Angular7 - 指令(Directives)

Angular7 - 指令(Directives) 首页 / Angular7入门教程 / Angular7 - 指令(Directives)

Angular中的指令是一个js类,它声明为@directive。我们在Angular中有3个指令。指令在下面列出-

Component 指令

这些构成了主要类,其中包含有关如何在运行时处理(processed),实例化(instantiated)和使用组件的详细信息。

Structural 指令

结构指令基本上是处理dom元素,结构性指令在指令之前带有*符号。如, * ngIf 和 * ngFor 。

Attribute 指令

属性指令处理更改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() { }
}

上面的文件具有指令,并且还具有selector属性。无论我们在selector中定义什么,都必须在分配自定义指令的视图中进行匹配。

在app.component.html视图中,让我们如下添加指令:

<!--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 的元素,这是必需的。该元素具有更改文本指令所应用的所有详细信息。

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

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

Change Text

在控制台中提供指令selector的元素的详细信息。由于我们已将 changeText 指令添加到了span标签,因此将显示span元素的详细信息。

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

趣谈Linux操作系统 -〔刘超〕

黄勇的OKR实战笔记 -〔黄勇〕

Spring Boot与Kubernetes云原生微服务实践 -〔杨波〕

TypeScript开发实战 -〔梁宵〕

架构实战案例解析 -〔王庆友〕

用户体验设计实战课 -〔相辉〕

代码之丑 -〔郑晔〕

Redis源码剖析与实战 -〔蒋德钧〕

郭东白的架构课 -〔郭东白〕

好记忆不如烂笔头。留下您的足迹吧 :)