属性型

属性指令改变的是宿主元素内部的属性,检测宿主元素的事件,并且可以捕获宿主元素输入的属性

  1. import { Directive, ElementRef, HostListener, Input } from '@angular/core';
  2. @Directive({
  3. selector: '[appHighlight]'
  4. })
  5. export class HighlightDirective {
  6. constructor(private el: ElementRef) { }
  7. @Input('appHighlight') highlightColor: string;
  8. @HostListener('mouseenter') onMouseEnter() {
  9. this.highlight(this.highlightColor || 'red');
  10. }
  11. @HostListener('mouseleave') onMouseLeave() {
  12. this.highlight(null);
  13. }
  14. private highlight(color: string) {
  15. this.el.nativeElement.style.backgroundColor = color;
  16. }
  17. }

结构型

*ngIf

当条件为假时,NgIf会从DOM中移除它的宿主元素,取消它监听过的那些DOM事件,从Angular变更检测中移除该组件,并销毁它。 这些组件和DOM节点可以被当做垃圾收集起来,并且释放它们占用的内存。

语法糖

*ngIf会被编译成:

  1. <ng-template [ngIf]="hero">
  2. <div class="name">{{hero.name}}</div>
  3. </ng-template>