2016-11-30 53 views
0

我正在考慮創建一個功能來隱藏和顯示Angular 2 Apps中的組件。我曾考慮過使用*ngIfngClass這樣做,但是,編寫代碼會很乏味。我現在正在考慮創建一個訪問DOM的服務,並且能夠在全球範圍內顯示和隱藏組件。如何使用Angular 2中的服務訪問DOM?

例如,我有DOM如下

<my-component-1></my-component-1> 
<my-component-2></my-component-2> 
<my-component-3></my-component-3> 
<my-component-4></my-component-4> 

我想有服務的功能如下

DomService.show('my-component-1') 

是否有可能這樣做使用本地角2,而不使用純JavaScript還是jQuery?

+0

這是'angular {Js/2}'的整點。不要處理...邏輯(組件/服務)中的DOM邏輯。如果您想操縱DOM,請在指令中執行。但是,如果您想感覺錯誤,請操縱DOM。 – Maxime

+0

我知道這一點。但我正在考慮更好更有效的方式。 – ljieyao

回答

0

當然,角度可以。 但是,你試圖做的是不正確的方式來處理angularjs。因爲,angularjs將數據與DOM綁定。

<my-component-1 ng-show="isHidden"></my-component-1> 
<my-component-2 ng-show="isHidden"></my-component-2> 
<my-component-3 ng-show="isHidden"></my-component-3> 
<my-component-4 ng-show="isHidden"></my-component-4> 

每當您更改isHidden的值時,它都會立即影響DOM。

Official Document

+0

'ng-show'用於angularJs,而不是angular2。 – Maxime

+0

如果我有超過10個組件,這不會起作用... – ljieyao