📜  Angular 6-指令

📅  最后修改于: 2020-10-28 05:26:14             🧑  作者: Mango


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

组件指令

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

结构指令

结构指令主要处理操纵dom元素。结构性指令在指令之前带有*符号。例如, * ngIf* ngFor

属性指令

属性指令处理更改dom元素的外观和行为。您可以创建自己的指令,如下所示。

如何创建自定义指令?

在本节中,我们将讨论要在组件中使用的自定义指令。自定义指令由我们创建,不是标准的。

让我们看看如何创建自定义指令。我们将使用命令行创建指令。使用命令行创建指令的命令是-

ng g directive nameofthedirective
e.g
ng g directive changeText

这就是它在命令行中的显示方式

C:\projectA6\Angular6App>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 (486 bytes)

以上文件(即change-text.directive.spec.tschange-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: '[appChangeText]'
})
export class ChangeTextDirective {
   constructor() { }
}

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

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

Welcome to {{title}}.

我们将在change-text.directive.ts文件中写入更改,如下所示:

change-text.directive.ts

import { Directive, ElementRef} from '@angular/core';
@Directive({
   selector: '[appChangeText]'
})
export class ChangeTextDirective {
   constructor(Element: ElementRef) {
      console.log(Element);
      Element.nativeElement.innerText = "Text is changed by changeText Directive. ";
   }
}

在上面的文件中,有一个名为ChangeTextDirective的类和一个构造函数,该构造函数采用ElementRef类型的元素,该元素是必需的。该元素具有应用了“更改文本”指令的所有详细信息。

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

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

ChangeText指令