import {Directive, ElementRef, HostListener, EventEmitter, Output} from '@angular/core';
@Directive({
selector: '[clickedOutside]'
})
export class ClickedOutsideDirective {
@Output()
public clickedOutside = new EventEmitter();
constructor(private _elemRef: ElementRef) {
}
@HostListener('document:click', ['$event'])
public onClick(event) {
const targetElement = event.target;
if (!targetElement) {
return;
}
/**
* In case the target element which was present inside the referred element
* is removed from the DOM before this method is called, then clickedInside
* will be false even if the clicked element was inside the ref Element. So
* if you don't want this behaviour then use [hidden] instead of *ngIf
*/
const clickedInside = this._elemRef.nativeElement.contains(targetElement);
if (!clickedInside && !this._elemRef.nativeElement.isSameNode(targetElement)) {
return this.clickedOutside.emit(event);
}
}
}
import {Component} from '@angular/core';
@Component({
selector: 'my-comp',
template: '<div colorFlip>This is just a Demo!</div>'
})
export class MyComp {}
5 回答
Simple-Directive-Demo . This is a very simple example to start with angular2 directive .
我有一个组件和指令 .
我使用指令来更新组件的视图 . 此外 directive's changeColor function 正在调用 component's changeColor function .
Component
Directive
简单来说 Component Directive 将是你的模板指令,我们在构建应用程序时使用了很多 - >在你的html中 - >
<custom-tag></custom-tag>
Structural Directive 是通过删除添加元素来修改DOM的 . 例子是
ngIf会添加div,如果为true,则删除if,如果它变为false .
最后是 Attribute Directive ,这个名字说明了一切..例如'attribute based directive'例如:
Angular指令有三种:
Angular2指南属性指令代码:https://github.com/guyoung/GyPractice-Angular2/tree/master/apps/attribute-directives
Angular2指南结构指令代码:https://github.com/guyoung/GyPractice-Angular2/tree/master/apps/structural-directives
这是一个示例指令 . 这为组件外部的单击完成添加了一个事件监听器 .
这可以使用如下:
只要有人点击外面,就会触发
close
app-comp
根据Angular2文档,指令用于更改DOM元素的行为 .
让我们创建一个指令,在mouseenter的情况下将div的backgroundcolor更改为红色,在mouseleave的情况下将其更改为黄色 .
第1步:创建组件
第2步:创建指令
第3步:注册指令