Angular(7) 学习资料 (3)指令

指令

在 Angular 中有三种类型的指令:

  • 组件 — 拥有模板的指令
  • 结构型指令 — 通过添加和移除 DOM 元素改变 DOM 布局的指令
  • 属性型指令 — 改变元素、组件或其它指令的外观和行为的指令

结构型指令

import { Directive, ElementRef, Input, HostListener, OnInit, Renderer2 } from '@angular/core'

@Directive({
  selector: '[appSpanHighLight]'
})
export class SpanHighLightDirective implements OnInit {
  // 指令的输入值
  @Input('appSpanHighLight') color: string

  constructor(private el: ElementRef, private render: Renderer2) {}

  ngOnInit() {
    // this.el.nativeElement.style.color = this.color || 'green'
    this.render.setStyle(this.el.nativeElement, 'color', this.color || 'green')
  }
  
  // 监听对应的事件 点击、鼠标的移入移出
  @HostListener('click') click() {}
  @HostListener('mouseenter') onMouseEnter() {}
  @HostListener('mouseleave') onMouseLeave() {}
}

Angular2 采用 AOT 静态编译模式,这种形式下需要我们的模板类型必须是稳定和安全的,直接使用 javascript 和 jquery 语言是不稳定,因为他们的编译不会提前发现错误,所以 angular2 才会选择 javascript 的超集 typescript 语言(这种语言编译期间就能发现错误)

为了能够支持跨平台,Angular 通过抽象层封装了不同平台的差异。比如定义了抽象类 Renderer、Renderer2 、抽象类 RootRenderer 等。此外还定义了以下引用类型:ElementRef、TemplateRef、ViewRef 、ComponentRef 和 ViewContainerRef 等。

推荐 Renderer2 操作 DOM,支持跨平台

属性型指令

例如 NgIf、NgFor 和 NgSwitch

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({ selector: '[appUnless]'})
export class UnlessDirective {
  private hasView = false;

  constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) { }

  @Input() set appUnless(condition: boolean) {
    if (!condition && !this.hasView) {
      this.viewContainer.createEmbeddedView(this.templateRef);
      this.hasView = true;
    } else if (condition && this.hasView) {
      this.viewContainer.clear();
      this.hasView = false;
    }
  }
}

`<p *appUnless="condition">Show this sentence unless the condition is true.</p>`

<ng-template> 是一个 Angular 元素,用来渲染 HTML。 它永远不会直接显示出来。事实上,在渲染视图之前,Angular 会把 <ng-template> 及其内容替换为一个注释。结构型指令会让 <ng-template> 正常工作。

// 这里的 * 会被展开为 <ng-template>
<div *ngIf="xxx">xxx</div>
<div *appUnless="xxx"></div>

<ng-template [ngIf]="xxx">
  <div>xxx</div>
</ng-template>
<ng-template [appUnless]="xxx">
  <div>xxx</div>
</ng-template>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值