Angular指令

1. 上面是指令

指令是为 Angular 应用程序中的元素添加额外行为的类。使用 Angular 的内置指令,你可以管理表单、列表、样式以及要让用户看到的任何内容。

2.指令分类

Angular 指令的不同类型如下:

  1. 组件 —— 带有模板的指令。这种指令类型是最常见的指令类型。
  2. 属性型指令 —— 更改元素、组件或其他指令的外观或行为的指令。
  3. 结构型指令 —— 通过添加和删除 DOM 元素来更改 DOM 布局的指令。

内置属性指令: ngClass, ngStyle,ngModel
内置结构指令: ngIf, ngFor, ngSwitch(自定义结构性指令还是很难得)
[ngIf] 可以用微语法糖简化, *ngIf

3.属性指令实例HighLight

  1. ng g directive
  2. 引入 ElementRef
  3. highlight.directive.ts
    可以从外部传值过来。
import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  @Input() appHighlight:string = '';
  @Input() defaultColor: string = '';


  constructor(private el: ElementRef) { 
    // console.log(el);
    // el.nativeElement.style.backgroundColor = "yellow"
  }
  @HostListener('mouseenter') onMouseEnter() {
    this.highLight(this.appHighlight || this.defaultColor || 'red');
  }
  @HostListener('mouseleave') onMouseLeave() {
    this.highLight('');
  }
  private highLight(color: string) {
    this.el.nativeElement.style.backgroundColor = color
  }

}

<!-- <p appHighlight>Highlight me!</p> -->
<div>
    <input type="radio" name="colors" (click)="color='lightgreen'" /> Green

    <input type="radio" name="colors" (click)="color='yellow'" /> Yellows

    <input type="radio" name="colors" (click)="color='cyan'" /> Cyan
</div>
<!--ngNonBindable停止插值表达式计算-->
<p  ngNonBindable [appHighlight]="color">Highlight me! {{1+1}}</p>
<!--没有加中括号,静态属性-->
<p [appHighlight]="color" defaultColor="violet">Highlight me, too!</p>

4.项目实例

import { Directive, Input, ElementRef, SecurityContext } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Directive({
  selector: '[appTextHighlight]'
})
export class TextHighlightDirective {
  @Input() set highlightColor(color: string) {
    this.color = color;
    this.updateHighlight();
  }

  @Input() set highlightText(hl: string) {
    const esc = hl.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    if (esc) {
      this.highlight = new RegExp(esc, 'ig');
    } else {
      this.highlight = null;
    }
    this.updateHighlight();
  }

  @Input() set appTextHighlight(text: string) {
    this.text = this.sanitizer.sanitize(SecurityContext.HTML, text);
    this.updateHighlight();
  }

  private color = '#ffd400';
  private text: string;
  private highlight: RegExp;

  constructor(
    private el: ElementRef<HTMLElement>,
    private sanitizer: DomSanitizer
  ) {}

  private updateHighlight() {
    if (this.text && this.el && this.el.nativeElement) {
      const elem = this.el.nativeElement;
      elem.innerHTML = this.highlight
        ? this.text.replace(
            this.highlight,
            `${this.color}">$&`
          )
        : this.text;
    } else {
      console.warn('Cannot apply highlight to null or non-HTML objects');
    }
  }
}

5. 结构型指令

import { Directive, TemplateRef, ViewContainerRef, Input } 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> -->
<p>
    The condition is currently
    <span [ngClass]="{'a': condition, 'b': !condition, 'unless': true}">{{condition}}</span>
    <button (click)="condition=!condition" [ngClass]="{'a': !condition, 'b': condition}"> Toggle condition to {{condition ? 'false' : 'true'}}</button>
</p>
<p *appUnless="condition" class="unless a">
    (A) This paragraph is displayed because the condition is false.
</p>
<p *appUnless="!condition" class="unless b">
    (B) Although the condition is true,
    this paragraph is displayed because appUnless is set to false.
</p>

你可能感兴趣的:(Angular,TypeScript,angular.js,typescript,javascript)