@Directive v / s @Component在Angular中

本文翻译自:@Directive v/s @Component in Angular

What is the difference between @Component and @Directive in Angular? Angular中@Component@Directive什么区别? Both of them seem to do the same task and have the same attributes. 他们两个似乎完成相同的任务,并具有相同的属性。

What are the use cases and when to prefer one over another? 用例是什么?何时优先使用一个?


#1楼

参考:https://stackoom.com/question/2D7ci/Directive-v-s-Component在Angular中


#2楼

A @Component requires a view whereas a @Directive does not. @Component需要视图,而@Directive则不需要。

Directives 指令

I liken a @Directive to an Angular 1.0 directive with the option restrict: 'A' (Directives aren't limited to attribute usage.) Directives add behaviour to an existing DOM element or an existing component instance. 我将@Directive类似于Angular 1.0指令,并带有以下 restrict: 'A'选项 restrict: 'A' (指令不限于属性用法。)指令将行为添加到现有DOM元素或现有组件实例中。 One example use case for a directive would be to log a click on an element. 指令的一个示例用例是记录对元素的单击。

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

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

Which would be used like so: 可以这样使用:

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

Components 组件

A component, rather than adding/modifying behaviour, actually creates its own view (hierarchy of DOM elements) with attached behaviour. 实际上,一个组件而不是添加/修改行为,而是使用附加的行为创建自己的视图(DOM元素的层次结构)。 An example use case for this might be a contact card component: 一个示例用例可能是联系卡组件:

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() {}
}

Which would be used like so: 可以这样使用:

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

ContactCard is a reusable UI component that we could use anywhere in our application, even within other components. ContactCard是可重用的UI组件,我们可以在应用程序中的任何位置使用它,甚至可以在其他组件中使用。 These basically make up the UI building blocks of our applications. 这些基本上构成了我们应用程序的UI构建块。

In summary 综上所述

Write a component when you want to create a reusable set of DOM elements of UI with custom behaviour. 当您要创建具有自定义行为的UI的可重用的DOM元素集时,请编写组件。 Write a directive when you want to write reusable behaviour to supplement existing DOM elements. 当您要编写可重用的行为以补充现有DOM元素时,请编写指令。

Sources: 资料来源:


#3楼

Components 组件

  1. To register a component we use @Component meta-data annotation. 要注册组件,我们使用@Component元数据注释。
  2. Component is a directive which uses shadow DOM to create encapsulated visual behavior called components. Component是一个指令,它使用影子DOM创建封装的可视行为(称为组件)。 Components are typically used to create UI widgets. 组件通常用于创建UI小部件。
  3. Component is used to break up the application into smaller components. 组件用于将应用程序分解为较小的组件。
  4. Only one component can be present per DOM element. 每个DOM元素只能存在一个组件。
  5. @View decorator or templateurl template are mandatory in the component. @View装饰器或templateurl模板在组件中是必需的。

Directive 指示

  1. To register directives we use @Directive meta-data annotation. 要注册指令,我们使用@Directive元数据注释。
  2. Directive is used to add behavior to an existing DOM element. 指令用于向现有DOM元素添加行为。
  3. Directive is use to design re-usable components. 指令用于设计可重复使用的组件。
  4. Many directives can be used per DOM element. 每个DOM元素可以使用许多指令。
  5. Directive doesn't use View. 指令不使用View。

Sources: 资料来源:

http://www.codeandyou.com/2016/01/difference-between-component-and-directive-in-Angular2.html http://www.codeandyou.com/2016/01/difference-between-component-and-directive-in-Angular2.html


#4楼

组件是带有模板的指令,而@Component装饰器实际上是具有面向模板功能的@Directive装饰器。


#5楼

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. 在Angular 2及更高版本中,“一切都是组件”。组件是我们通过在现有组件中添加功能的自定义元素和属性来构建和指定页面上的元素和逻辑的主要方式。

http://learnangular2.com/components/ http://learnangular2.com/components/

But what directives do then in Angular2+ ? 但是,在Angular2 +中会执行哪些指令?

Attribute directives attach behaviour to elements. 属性指令将行为附加到元素。

There are three kinds of directives in Angular: Angular中有三种指令:

  1. Components—directives with a template. 组件-带有模板的指令。
  2. Structural directives—change the DOM layout by adding and removing DOM elements. 结构化指令-通过添加和删除DOM元素来更改DOM布局。
  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 https://angular.io/docs/ts/latest/guide/attribute-directives.html

So what's happening in Angular2 and above is Directives are attributes which add functionalities to elements and components . 因此,在Angular2及更高版本中发生的是,伪指令是为元素组件添加功能的属性。

Look at the sample below from Angular.io: 看下面来自Angular.io的示例:

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

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

So what it does, it will extends you components and HTML elements with adding yellow background and you can use it as below: 如此做,它将通过添加黄色背景扩展您的组件和HTML元素,您可以按以下方式使用它:

<p myHighlight>Highlight me!</p>

But components will create full elements with all functionalities like below: 但是组件将创建具有所有功能的完整元素,如下所示:

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)
  }
}

and you can use it as below: 您可以按以下方式使用它:

<my-component></my-component>

When we use the tag in the HTML, this component will be created and the constructor get called and rendered. 当我们在HTML中使用标记时,将创建此组件,并调用并呈现构造函数。


#6楼

Change detection 变更检测

Only @Component can be a node in the change detection tree. 只有@Component可以成为更改检测树中的节点。 This means that you cannot set ChangeDetectionStrategy.OnPush in a @Directive . 这意味着你不能设置ChangeDetectionStrategy.OnPush@Directive Despite this fact, a Directive can have @Input and @Output properties and you can inject and manipulate host component's ChangeDetectorRef from it. 尽管如此,指令仍可以具有@Input@Output属性,并且您可以从中注入和操作主机组件的ChangeDetectorRef So use Components when you need a granular control over your change detection tree. 因此,当您需要对变更检测树进行精细控制时,请使用“组件”。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值