@Directive V / S @Component在angular2 [英] @Directive v/s @Component in angular2

查看:671
本文介绍了@Directive V / S @Component在angular2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是 @Component @Directive Angular2
他们两个似乎做相同的任务并具有相同的属性。

What is the difference between @Component and @Directive in Angular2? Both of them seem to do the same task and have the same attributes.

希望有人回复,有什么用例和时对另一对preFER?

Hope somebody replies, what are the use cases and when to prefer on over another?

推荐答案

一个@Component需要一个视图,而一个@Directive没有。

<击>我比喻一个@Directive到角1.0指令与选项限制:'A' (指令不限属性的使用。 )指令行为添加到现有的DOM元素。一个例子使用的情况下@Directive将鼠标悬停新增的一大亮点。

I liken a @Directive to an Angular 1.0 directive with the option restrict: 'A' (Directives aren't limited attribute usage.) Directives add behaviour to an existing DOM element. One example use case for @Directive would be to add a highlight on mouse hover.

import {Directive} from 'angular2/core'';

@Directive({
    selector: "[log-on-click]",
    hostListeners: {
        'click': 'onClick()'
    }
})
class LogOnClick {

    constructor() {}

    onClick() { console.log('Element clicked!'); }
}

这将是使用像这样:

Which would be used like so:

<button log-on-click>I log when clicked!</button>

部件

一个组成部分,而不是添加行为,以现有的DOM元素,实际上创建它自己的视图(DOM元素的层次)与附加行为。一个例子使用的情况下,这可能是一个名片组件:

Components

A component, rather than adding behaviour to an existing DOM element, actually creates it's own view (hierarchy of DOM elements) with attached behaviour. An example use case for this might be a contact card component:

import {Component, View} from 'angular2/core'';

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

这将是使用像这样:

Which would be used like so:

<contact-card></contact-card>

ContactCard是,我们可以在我们的应用程序在任何地方使用,即使在其他部件可重复使用的UI组件。这些基本上构成了我们的应用程序的UI构建块。

ContactCard is a reusable UI component that we could use anywhere in our application, even within other components. These basically make up the UI building blocks of our applications.

当你想创建一个可重复使用的一套定制的UI行为的DOM元素写一个组成部分。当你想要编写可重用的行为以补充现有的DOM元素写指令。

Write a component when you want to create a reusable set of DOM elements of UI with custom behaviour. Write a directive when you want to write reusable behaviour to supplement existing DOM elements.

来源:

  • @Directive documentation
  • @Component documentation
  • Helpful blog post

这篇关于@Directive V / S @Component在angular2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆