Skip to content

【NG】Directive #39

@xinbaihui

Description

@xinbaihui

定义和用法

https://angular.cn/api/core/Directive#description

  • 用法:用 @ Directive 装饰一个类,这个类就是Angular 指令, 可以在模板中使用
  • 用途:为 DOM 中的元素添加自定义行为
  • @ Directive 提供配置元数据,用于决定该指令在运行期间要如何处理、实例化和使用。

分类

在 Angular 中有三种类型的指令:

  • 组件 — 拥有模板的指令
  • 结构型指令 — 通过添加和移除 DOM 元素改变 DOM 布局的指令, eg: NgIf, NgFor, NgSwitch
  • 属性型指令 — 改变DOM元素的外观和行为的指令, eg: NgStyle

Structural Directive

https://angular.cn/guide/structural-directives

  • NgIf 为何是删除元素而不是隐藏? -- 性能和内存上的优化
  • NgIf 和 ngIf:NgIf 引用的是指令的类名,而 ngIf 引用的是指令的属性名
  • (*)前缀: 语法糖
  • 如何编写结构型指令

Attribute Directive

  • 为什么要写成 [ngSwitch] 而不是 *ngSwitch ?
    NgSwitch 本身不是结构型指令,而是一个属性型指令,它控制其它两个 switch 指令的行为。
  • 一个元素只能有一个结构型指令,可以有多个属性型指令

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions