What is the difference between component and directive?

前端 未结 7 823
感动是毒
感动是毒 2020-11-29 20:01

I have just started working with Angular 2.

I was wondering what are the differences between components and directives in Angular 2?

7条回答
  •  一向
    一向 (楼主)
    2020-11-29 20:39

    Summary:

    A component is a directive with an associated view (i.e. HTML to be rendered). All components are directives, but not all directives are components. There are three types of directives:

    • Component: A view with associated behaviour. This type of directive actually adds DOM elements
    • Attribute directives: Can be attached to DOM elements (and components since they are DOM elements) to modify the appearance or behaviour of an element.
    • Structural directives: Can be attached to DOM elements (and components since they are DOM elements) to modify the DOM layout. Structural directives start with a * and actually add or remove DOM element. For example *ngIf which can insert or remove an DOM element (or angular component which is a custom DOM element, but still a DOM element).

    Example:

    import { Component, HostListener, HostBinding, Directive, ElementRef } from '@angular/core';
    
    @Directive({
      selector: '[appHighlight]'
    })
    export class HighlightDirective {
      constructor(el: ElementRef) {
        el.nativeElement.style.backgroundColor = 'yellow';
     }
    }
    
    @Component({
      selector: 'app-root',
      template: `
        
    Hi there
    `, styleUrls: ['./app.component.scss'], }) export class AppComponent { myBool:boolean = true; }

    In the above example we can observe the following:

    • The component AppComponent has a template with a
      element which displays, hi there.
    • The attribute directive HighlightDirective is located on the
      element. This means it will manipulate the behaviour of the
      element. In this case it will highlight the text and will turn it yellow.
    • The structural directive *ngIf is also located on the
      element and will determine if the element is to be inserted. The
      will be conditionally shown depending on whether the expression myBool can be coerced to true.

提交回复
热议问题