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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- Ack.vim在Windows上“没有这样的文件或目录”错误
- ng-conf-2017 - Angular Form Validation
- 并行Scala流的内存消耗
- WebService大讲堂之Axis2(3):使用services.xml文
- 使用批处理,根据文件类型C、C++、java选择执行程
- WebService出现"因 URL 意外地以 结束,请求
- 【ionic+angularjs】$ionicScrollDelegate list列
- Bootstrap文件(图片)上传插件File Input进阶使
- angularjs – 使用ng-repeat {ANGULAR.JS}加载JS
- shell 数组操作
热点阅读