Angular 9 : Use component as directive

Viewed 919

Recently Im reading source of nebular, an angular ui framework, I have questions about the following code:

@Component({
  selector: '[nbMenuItem]',
  templateUrl: './menu-item.component.html',
  animations: [
    ...
  ],
})
export class NbMenuItemComponent implements DoCheck, AfterViewInit, OnDestroy {
  @Input() menuItem = <NbMenuItem>null;

  @Output() hoverItem = new EventEmitter<any>();
  @Output() toggleSubMenu = new EventEmitter<any>();
  @Output() selectItem = new EventEmitter<any>();
  @Output() itemClick = new EventEmitter<any>();

This should be a component, and here's how it use:

@Component({
  selector: 'nb-menu',
  styleUrls: ['./menu.component.scss'],
  template: `
    <ul class="menu-items">
      <ng-container *ngFor="let item of items">
        <li nbMenuItem *ngIf="!item.hidden"
            [menuItem]="item"
            [class.menu-group]="item.group"
            (hoverItem)="onHoverItem($event)"
            (toggleSubMenu)="onToggleSubMenu($event)"
            (selectItem)="onSelectItem($event)"
            (itemClick)="onItemClick($event)"
            class="menu-item">
        </li>
      </ng-container>
    </ul>
  `,
})
export class NbMenuComponent implements OnInit, AfterViewInit, OnDestroy {
   ...
}

My question is, why nbMenuItem can be used as a directive, it is annotated by @Component, why? I haven't found anything about this in the angular document.

2 Answers

All components are directives, but not all directives are components. i.e. a component is a directive with a template. as defined in the angular docs

that being said, the primary reason why you can use nbMenuItem as an attribute of a DOM element is because of the selector for NbMenuItemComponent.

by putting brackets around the selector, that informs Angular of how it can be used. in this case [nbMenuItem] means this can be use as an attribute of a DOM element, and as such as an directive.

In angular 9, attribute selector is inherited from Directive decorator. See Angular Component

Related