Angular7 指令
Angular 中的 Directives 是一个 js 类,它被声明为 @directive。我们在 Angular 中有 3 个指令。指令如下:
组件指令
这些构成了主类,详细说明了在运行时应该如何处理、实例化和使用组件。
结构指令
结构指令主要处理 dom 元素的操作。结构指令在指令前有一个 * 符号。例如, *ngIf and *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 { }
The 更改文本指令 类包含在上述文件的声明中。该类也是从下面给出的文件中导入的:
更改文本指令
import { Directive } from '@angular/core'; @Directive({ selector: '[changeText]' }) export class ChangeTextDirective { constructor() { } }
上面的文件有一个指令,它也有一个选择器属性。无论我们在选择器中定义什么,都必须在我们分配自定义指令的视图中匹配。
在 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>
我们将更改写入 更改文本.directive.ts 文件如下:
更改文本.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."; } }
在上面的文件中,有一个类叫做 更改文本指令 和一个构造函数,它接受 type 的元素 元素引用 ,这是强制性的。该元素具有所有细节 更改文本 指令被应用。
我们添加了 console.log 元素。可以在浏览器控制台中看到相同的输出。如上所示,元素的文本也发生了变化。
现在,浏览器将显示以下内容:
在控制台中给出指令选择器的元素的详细信息。由于我们添加了 更改文本 指向 span 标签的指令,会显示 span 元素的详细信息。