属性型
属性指令改变的是宿主元素内部的属性,检测宿主元素的事件,并且可以捕获宿主元素输入的属性
import { Directive, ElementRef, HostListener, Input } from '@angular/core';@Directive({selector: '[appHighlight]'})export class HighlightDirective {constructor(private el: ElementRef) { }@Input('appHighlight') highlightColor: string;@HostListener('mouseenter') onMouseEnter() {this.highlight(this.highlightColor || 'red');}@HostListener('mouseleave') onMouseLeave() {this.highlight(null);}private highlight(color: string) {this.el.nativeElement.style.backgroundColor = color;}}
结构型
*ngIf
当条件为假时,NgIf会从DOM中移除它的宿主元素,取消它监听过的那些DOM事件,从Angular变更检测中移除该组件,并销毁它。 这些组件和DOM节点可以被当做垃圾收集起来,并且释放它们占用的内存。
语法糖
*ngIf会被编译成:
<ng-template [ngIf]="hero"><div class="name">{{hero.name}}</div></ng-template>
