因为你的场景是隐藏一个元素而不是操纵DOM结构,你可以创建一个属性指令来应用到你的<div>
。
查找波纹管的一个解决方案:
指令
import {Directive, ElementRef, EventEmitter, HostListener, Input, Output} from '@angular/core';
@Directive({
selector: '[showMe]'
})
export class ShowMeDirective {
private _show: boolean;
/**
* Emmit changes in 'showMe'.
* @type {EventEmitter}
*/
@Output('showMeChange')
public showChange = new EventEmitter();
/**
* Called when the 'showMe' expression changes.
* @param show Whether to show or hide the element.
*/
@Input('showMe')
public set show(show: boolean) {
this.elRef.nativeElement.style.display = show ? null : 'none';
this._show = show;
}
/**
* Get whether the element is visible.
* @returns {boolean}
*/
public get show() {
return this._show;
}
/**
* Ctor.
* @param elRef References the element
*/
constructor(private elRef: ElementRef) {
}
/**
* Stop propagating click event for current element.
* @param $event Event arguments
*/
@HostListener('click', ['$event'])
public onElementClick($event) {
$event.stopPropagation();
}
/**
* When the document is clicked then the element is hidden.
*/
@HostListener('document:click')
public onDocumentClick() {
if (this.show !== false) {
this.show = false;
this.showChange.emit(false);
}
}
}
用法
<div [(showMe)]="show" style="line-height: 50px; font-weight: bold;">
Contents of DIV
</div>
<p>DIV is visible: {{ show }}</p>
<br/>
<button (click)="show = true; $event.stopPropagation();" type="button">Show DIV</button>
show
最初被设置为一个值(例如:show = false
)。
说明
的showMe
指令定义的输入(与@input注释),它是指令属性本身showMe
。这也允许从外部传递这个值并作出相应的反应。因此,这是一个设置器,它设置style.display
值并触发更改事件。
showMe
指令还定义了一个输出(用@Output标注),它被称为showMeChange
。这是为了反映模型中的变化,以便使用该指令的组件将相应地改变它的属性。
showMe
指令使用@HostListener('click', ['$event'])
订阅其应用元素的click
事件。因此,当点击时,事件不会传播,以便它不会被处理程序拦截。
showMe
指令订阅document.click
事件以便使元素不可见。
<button>
处理click
事件,但他也通过执行$event.stopPropagation();
阻止click
冒泡到其他元素。
因为showMe
指令定义了showMe
输入和showMeChange
输出它可以写为<div [showMe]="show" (showMeChange)="show = $event;">
。但它也可以写成<div [(showMe)]="show">
(香蕉盒装风格)。
因此,您可以从指令内部操作可见性,但也可以从指令外部操作,从而传递数据来回传递。
注:以下if
代码防止射击时的价值不是从指令中更改的事件:
public onDocumentClick() {
if (this.show !== false) {
this.show = false;
this.showChange.emit(false);
}
}
您可以为创建指令。请访问[此链接](https://christianliebel.com/2016/05/angular-2-a-simple-click-outside-directive/)或直接使用此[npm包](https://github.com/chliebel/angular2单击-外)。 –
你能展示更多代码吗?显示代码是什么样的?什么样的HTML? – DeborahK