因爲你的場景是隱藏一個元素而不是操縱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