Welcome to %s forums

<No. 1 Community for developers, by developers/>

Login Register

Interview Question - What is the difference between Angular component and directive?

Get support on Angular & Typescript related technology.
Post Reply
admin
Site Admin
Posts: 45

Interview Question - What is the difference between Angular component and directive?

Post by admin » Mon Oct 14, 2019 6:11 pm

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

Used to:
Components - Components are typically used to create UI widgets.
Directive - Directives is used to add behavior to an existing DOM element.

Components - Component is used to break up the application into smaller components.
Directive - Directive is use to design re-usable components.

Per DOM element:
Components - Only one component can be present per DOM element.
Directive - Many directive can be used in a per DOM element.

@View:
Components - @View decorator or templateurl template are mandatory in the component.
Directive - Directive don’t have View.

Pipes:
Components - Component is used to define pipes.
Directive - You can’t define Pipes in directive.

viewEncapsulation:
Components - viewEncapsulation can be define in components because they have views.
Directive - Directive don’t have views. So you can’t use viewEncapsulation in directive.

Example:
Components -

Code: Select all

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

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

<message></message>
Directive -

Code: Select all

import {Directive} from 'angular2/angular2';

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

    constructor() {}

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

<button myDirective>Click here</button>

Post Reply