Angular 中的@Directive 与@Component

@Directive vs @Component in Angular

Angular中的@Component@Directive有什么区别? 两者似乎都在做同样的工作,具有相同的属性。

有哪些用例以及何时优先选择一个?

@Component 需要视图,而@Directive 不需要。

指令

我将 @Directive 比作带有选项 restrict: 'A' 的 Angular 1.0 指令(指令不限于属性使用。)指令添加现有 DOM 元素或现有组件实例的行为。指令的一个示例用例是记录对元素的点击。

import {Directive} from '@angular/core';

@Directive({
    selector: "[logOnClick]",
    hostListeners: {
        'click': 'onClick()',
    },
})
class LogOnClick {
    constructor() {}
    onClick() { console.log('Element clicked!'); }
}

可以这样使用:

<button logOnClick>I log when clicked!</button>

组件

一个组件,而不是 adding/modifying 行为,实际上创建了它自己的带有附加行为的视图(DOM 元素的层次结构)。一个示例用例可能是名片组件:

import {Component, View} from '@angular/core';

@Component({
  selector: 'contact-card',
  template: `
    <div>
      <h1>{{name}}</h1>
      <p>{{city}}</p>
    </div>
  `
})
class ContactCard {
  @Input() name: string
  @Input() city: string
  constructor() {}
}

可以这样使用:

<contact-card [name]="'foo'" [city]="'bar'"></contact-card>

ContactCard 是一个可重用的 UI 组件,我们可以在应用程序的任何地方使用它,甚至可以在其他组件中使用。这些基本上构成了我们应用程序的 UI 构建块。

总结

当您想要创建具有自定义行为的 UI 的 DOM 元素的可重用集时,请编写一个组件。当您想编写可重用的行为来补充现有的 DOM 元素时,请编写一个指令。

来源:

组件

  1. 要注册组件,我们使用 @Component meta-data 注释。
  2. Component 是一个指令,它使用阴影 DOM 来创建称为组件的封装视觉行为。组件通常用于创建 UI 小部件。
  3. 组件用于将应用程序分解成更小的组件。
  4. 每个 DOM 元素只能存在一个组件。
  5. @View 装饰器或 templateurl 模板在组件中是必需的。

指令

  1. 我们使用 @Directive meta-data 注释来注册指令。
  2. 指令用于向现有 DOM 元素添加行为。
  3. 指令用于设计 re-usable 个组件。
  4. 每个 DOM 元素可以使用许多指令。
  5. 指令不使用视图。

来源:

https://www.devdiscuss.com/difference-between-component-and-directive-in-angular-2/

组件是一个带有模板的指令,@Component 装饰器实际上是一个 @Directive 装饰器,扩展了面向模板的特性。

In Angular 2 and above, “everything is a component.” Components are the main way we build and specify elements and logic on the page, through both custom elements and attributes that add functionality to our existing components.

http://learnangular2.com/components/

但是 Angular2+ 中的指令是做什么的?

Attribute directives attach behaviour to elements.

There are three kinds of directives in Angular:

  1. Components—directives with a template.
  2. Structural directives—change the DOM layout by adding and removing DOM elements.
  3. Attribute directives—change the appearance or behaviour of an element, component, or another directive.

https://angular.io/docs/ts/latest/guide/attribute-directives.html

所以 Angular2 及更高版本中发生的事情是 指令 是向 元素 组件 [= 添加功能的属性39=].

查看下面来自 Angular.io 的示例:

import { Directive, ElementRef, Input } from '@angular/core';

@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
    constructor(el: ElementRef) {
       el.nativeElement.style.backgroundColor = 'yellow';
    }
}

那么它的作用是,它会通过添加黄色背景扩展您的组件和 HTML 元素,您可以按如下方式使用它:

<p myHighlight>Highlight me!</p>

但是组件将创建具有如下所有功能的完整元素:

import { Component } from '@angular/core';

@Component({
  selector: 'my-component',
  template: `
    <div>Hello my name is {{name}}. 
      <button (click)="sayMyName()">Say my name</button>
    </div>
   `
})
export class MyComponent {
  name: string;
  constructor() {
    this.name = 'Alireza'
  }
  sayMyName() {
    console.log('My name is', this.name)
  }
}

您可以按如下方式使用它:

<my-component></my-component>

当我们在 HTML 中使用标签时,将创建此组件并调用和呈现构造函数。

变更检测

只有 @Component 可以成为变化检测树中的节点。这意味着您不能在 @Directive 中设置 ChangeDetectionStrategy.OnPush。尽管如此,指令可以具有 @Input@Output 属性,您可以从中注入和操作宿主组件的 ChangeDetectorRef。因此,当您需要对变更检测树进行精细控制时,请使用组件。

在编程上下文中,指令为编译器提供指导,以改变它处理输入的方式,即改变某些行为。

“Directives allow you to attach behavior to elements in the DOM.”

指令分为 3 类:

  • 属性
  • 结构
  • 组件

是的,在Angular 2,组件是指令的一种。 根据文档,

“Angular components are a subset of directives. Unlike directives, components always have a template and only one component can be instantiated per an element in a template.”

Angular 2 组件是 Web 组件 概念的实现。 Web Components 由几种独立的技术组成。您可以将 Web 组件视为使用开放 Web 技术创建的可重用用户界面小部件。

  • 所以在总结指令中我们将行为附加到DOM中的元素的机制,包括结构, 属性和组件类型。
  • 组件是特定类型的指令,它允许我们 利用 Web 组件功能 又名可重用性 - 封装的、可重用的元素在我们的应用程序中可用。

如果你参考官方 angular 文档

https://angular.io/guide/attribute-directives

Angular中有3种指令:

  1. 组件——带有模板的指令。
  2. 结构指令——通过添加和删除 DOM 元素来更改 DOM 布局。例如 *ngIf
  3. 属性指令—更改元素、组件或其他指令的外观或行为。例如 [ngClass].

随着应用程序的增长,我们发现很难维护所有这些代码。出于可重用性目的,我们将智能组件和哑组件的逻辑分开,我们使用指令(结构或属性)在 DOM.

中进行更改

组件

组件是 Angular 应用程序最基本的 UI 构建块。 Angular 应用程序包含 Angular 组件树。我们在 Angular 中的应用程序构建在 组件树 上。每个组件都应该有它的模板、样式、生命周期、选择器等。因此,每个组件都有它的结构您可以将它们视为一个独立的小型 Web 应用程序,具有自己的模板和逻辑,并且可以与其他组件进行通信和一起使用。

组件的示例 .ts 文件:

import { Component } from '@angular/core';

@Component({
    // component attributes
    selector: 'app-training',
    templateUrl: './app-training.component.html',
    styleUrls: ['./app-training.component.less']
})

export class AppTrainingComponent {
    title = 'my-app-training';
}

及其 ./app.component.html 模板视图:

Hello {{title}}

然后您可以在其他组件中渲染 AppTrainingComponent 模板及其逻辑(将其添加到模块后)

<div>
   <app-training></app-training>
</div>

结果将是

<div>
   my-app-training
</div>

因为 AppTrainingComponent 在此处呈现

more about Components

指令

指令更改现有 DOM 元素的外观或行为。例如 [ngStyle] 是一个指令。指令 可以扩展组件 (可以在它们内部使用)但它们 不会构建整个应用程序 。假设他们只支持组件。 他们没有自己的模板(当然,你可以用他们来操作模板)。

示例指令:

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {

  constructor(private el: ElementRef) { }

  @Input('appHighlight') highlightColor: string;

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight(this.highlightColor || 'red');
  }

  private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }
}

及其用法:

<p [appHighlight]="color" [otherPar]="someValue">Highlight me!</p>

more about directives

组件是封装视图和逻辑的单个单元,而指令用于增强组件或 dom 元素的行为,它没有任何模板。

组件扩展指令,因此每个组件都是一个指令。

  • 组件和指令都可以有生命周期钩子、输入、输出、提供者和查询。
  • 组件还可以有viewproviders、changedetectionstrategy、 模板、样式和视图封装。

We can use components to build a featureful element and directives to create customizations for the element.

最简单的答案

组件:一个主要的构建块,用来添加一些DOM elements/Html.

指令:用于在DOMelements/HTML.

中添加一些表达式、条件和循环

指令:

指令 类 为元素添加额外的行为。

不同类型的指令是:

  1. COMPONENTS: 这些指令包含模板
  2. 属性指令:这些类型的指令改变元素、组件、其他指令的视图或行为
  3. 结构指令:这些指令通过添加或删除 DOM 元素来更改 DOM 布局。

这是 Angular13

的最新更新

@Component 只是 @Directive 的子类。在深入研究之前,我们必须了解什么是 @Directive...

@Directive 是一个装饰器,用于指示 DOM 添加新元素或删除或修改现有元素。因此,每当 Angular 遇到任何装饰器时,它都会在 运行 时间处理它们并根据它修改 DOM。

我们可以使用@Directive 创建指令,如下所示

@Directive({
  selector: '[demoButtonColor]'
})
export class DemoButtonColorDirective {
  constructor(private elementRef: ElementRef) { };
  ngOnInit() {
    this.elementRef.nativeElement.style.backgroundColor = 'red';
  }
}

在HTML

中的用法
<button demoButtonColor>RED BUTTON</button>

现在让我们看看什么是@Component装饰器

@Component 是@Directive 的子类,具有一项附加功能。使用@Component,我们可以创建我们的 HTML 模板,它可以在 运行 时间被注入到 DOM 中。

@Component({
  selector: 'demo-color',
  template: '<h1>Hello There!</h1>'
})
class DemoColorComponent {}

我们可以在任何其他组件中重用它,如下所示

<div>
  <demo-color></demo-color>
</div>

总结一下, 使用@Directive 创建自定义指令,可用于修改元素或结构DOM。如果您想创建具有自定义行为的可重用 UI 组件,请使用 @Component。