加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

ng2自定义指令 directive

发布时间:2020-12-17 09:39:33 所属栏目:安全 来源:网络整理
导读:1、自定义指令 /* * Directive: 指令模块 * ElementRef: 获取节点 * Input: 获取输入内容 * Renderer: 渲染新节点 * HostListener: 这是监听事件的,绑定时间 * * 注意: * 1. 指令的名称要使用中括号括起来 * 2. html中使用的时候,不需要中括号 * 3. 构造模板

1、自定义指令

/*
 * Directive: 指令模块
 * ElementRef: 获取节点
 * Input: 获取输入内容
 * Renderer: 渲染新节点
 * HostListener: 这是监听事件的,绑定时间
 *
 * 注意:
 * 1. 指令的名称要使用中括号括起来
 * 2. html中使用的时候,不需要中括号
 * 3. 构造模板中传递参数的时候,如果是字符串,那么要单引号: [myHighlight]="'blue'"
 */
import {Directive,ElementRef,HostListener,Input,Renderer} from '@angular/core';
@Directive({
  selector: '[myHighlight]'
})
export class OneDirective {
  constructor(private el:ElementRef,private renderer:Renderer) {

  }

  // 给myHighlight指令定义一个输入变量(外部调取这个指令传递的参数)
  @Input("myHighlight") chColor: string;

  @HostListener("click") onClick() {
    // 调用函数,传递指令外部获取的颜色
    this.changeColor(this.chColor);
  }
  // 自定义函数
  public changeColor(color: string) {
    this.renderer.setElementStyle(this.el.nativeElement,"background-color",color);
  }
}

2、app.module.ts主模块中引入指令

import {HighLight} from "../directive/high-light.directive.ts"
@ngModule({
    declarations: [
        HighLight
    ]
})

3、模板中使用指令

<p myHighlight="yellow">
    自定义指令
</p>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读