angular学习笔记(四)指令和管道

一、指令

1.1 内置指令

1.1.1 *ngIf

1.1.2 [hidden]

1.1.3 *ngFor

1.2 自定义指令

在 Angular 中,属性型指令的创建至少需要一个带有 @Directive 装饰器的控制器类。这个装饰器指定了一个选择器名称,用于标识与指令相关联的属性名称。控制器类实现了指令的功能行为。

创建指令为: ng g d directives/hover

1.2.1 创建属性型指令

需求:实现鼠标在元素上悬停时,改变起背景颜色;鼠标移开时,背景颜色消失;鼠标点击时,字体变大;鼠标松开时,字体恢复原样的功能。

创建 background-exed.directive.ts 文件,实现如下代码:

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

@Directive({
  selector: '[appBackgroundExed]',
})
export class BackgroundExedDirective implements AfterViewInit {
  @Input() highLightColor: string = ''
  constructor(private elementRef: ElementRef, private renderer: Renderer2) {}
  // 视图初始化完成后,设置背景s颜色为黄色
  ngAfterViewInit(): void {
    // 写法较丑,不推荐
    // this.elementRef.nativeElement.style.background = 'yellow'
    // 推荐这种写法 Renderer
    this.renderer.setStyle(
      this.elementRef.nativeElement,
      'background',
      'yellow'
    )
  }

  // 为节点动态注入class
  @HostBinding('class.pressed')
  isPressed: boolean = false

  //绑定监听事件
  @HostListener('mouseenter')
  onMouseEnter(): void {
    this.highLight(this.highLightColor)
  }

  @HostListener('mouseleave')
  onMouseLeave(): void {
    this.highLight('')
  }

  @HostListener('mousedown')
  onMouseDown(): void {
    this.isPressed = true
  }

  @HostListener('mouseup')
  onMouseUp(): void {
    this.isPressed = false
  }

  // 修改背景颜色
  private highLight(color: string): void {
    // this.elementRef.nativeElement.style.background = color;
    this.renderer.setStyle(this.elementRef.nativeElement, 'background', color)
  }
}

具体细节参考:详解Angular中自定义创建指令的方法-木庄网络博客 (muzhuangnet.com)

二、管道

作用:格式化组件模板的数据

 2.1 内置管道

 

2.2 自定义管道

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值