700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > angular自定义指令 directive

angular自定义指令 directive

时间:2020-08-17 18:04:29

相关推荐

angular自定义指令 directive

在命令行窗口下用 CLI 命令ng generate directive在app/directivess文件夹下创建指令类文件。

ng generate directive directives/highlight

可也一自己手动新建文件,highlight.directive.ts

app/directives/highlight.directive.ts的内容如下:

import { Directive, ElementRef, HostListener, Input } from '@angular/core';@Directive({selector: '[appHighlight]' // 指令名称})export class HighlightDirective {el:ElementRefconstructor(el: ElementRef) {this.el = el;}@Input('appHighlight') highlightColor: string; // 传进来的颜色@HostListener('mouseenter') onMouseEnter() { // 绑定事件this.highlight(this.highlightColor || 'red');}@HostListener('mouseleave') onMouseLeave() {this.highlight(null);}private highlight(color: string) {this.el.nativeElement.style.backgroundColor = color;}}

在app.module.ts中

@NgModule({declarations: [...HighlightDirective,...],...})

使用:

<p[appHighlight]="'pink'">Highlightme!</p> // 粉色

<pappHighlight>Highlightme!</p> // 红色

参考文献:angular官网-directive

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。