Difference between component and directive in Angular 2

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


Difference between component and directive in Angular 2 ?



Component and Directive is very important in Angular 2. Today we sharing difference between component and directive in Angular 2.

Components
Directive
For register component we use @Component meta-data annotation.
For register directives we use @Directive meta-data annotation.

Component is a directive which use shadow DOM to create encapsulate visual behavior called components.  Components are typically used to create UI widgets.

Directives is used to add behavior to an existing DOM element.


Component is used to break up the application into smaller components.

Directive is use to design re-usable components.
Only one component can be present per DOM element.

Many directive can be used in a per DOM element.
@View decorator or templateurl template are mandatory in the component.

Directive don’t have View.
Component is used to define pipes.

You can’t define Pipes in directive.
viewEncapsulation can be define in components because they have views.
Directive don’t have views. So you can’t use viewEncapsulation in directive.
Example –

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

@Component({
  selector: 'message'
})
@View({
  template: `
      <h1>Hello Angular {{version}}</h1>
  `
})
class Message {
  constructor(public version: string) {}
}

<message></message>
Example –

import {Directive} from 'angular2/angular2';

@Directive({
    selector: "[myDirective]",
    hostListeners: {
        'click': 'showMessage()'
    }
})
class Message {

    constructor() {}

    showMessage() { console.log('Hello Directive'); }
}

<button myDirective>Click here</button>









Keywords - component vs directive , Difference between component and directive in Angular 2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值