2017-02-09 73 views
1

我必須隱藏上述父視圖。以角度2隱藏父視圖

enter image description here 以下是我的代碼。當我點擊任何一個箱子的父母應該隱藏孩子應該出現。

 <app-navbar></app-navbar> 
     <div class="container" [style.height]='height' style="margin-top: 7%;"> 
      <div class="row box_rpad"> 
       <app-box-layout 
           (display)="onDisplay($event)" 
           *ngFor="let color of colors let i=index" 
           [color]='color.hex' 
           [text]='color.name' 
           [id]='i'> 
       </app-box-layout>    
      </div> 
     </div> 

     <!-- CHILD ROUTES --> 
     <div class="container"> 
      <router-outlet></router-outlet> 
     </div> 
+0

您不僅可以使用父組件訂閱的服務,並且子組件可以在點擊時更新訂閱「隱藏」變量,反之亦然? –

回答

1

以下應該做的伎倆....不是最佳的這種解決方案,但至少它可以按你的想法工作。所以,只是包裝要隱藏一個布爾值,一個div裏面的東西,e.g

<div *ngIf="notSelected"> 
    <!-- your code here --> 
</div> 

而就設置布爾爲false在同一個函數,你處理一下父補償一些框的事件。

clicked() { 
    .... 
    this.notSelected = false; 
} 

要告知家長需要再次顯示從子導航回到父母的時候,你可以使用Subject。因此,在你的父母宣佈主題:

public static showParent: Subject<any> = new Subject(); 

,並在你的父類的構造訂閱變化:

constructor(...) { 
    ParentComponent.showParent.subscribe(res => { 
    this.notSelected = true; // show parent component 
    }) 
} 

,並在你的孩子,導航回父面前,無論該事件可能是:

returnToParent() { 
    ParentComponent.showParent.next(false); 
    this.router.navigate...... 
} 
+0

是它的工作夥伴。但是在導航主頁後沒有內容。主頁變空白:( –

+0

@IamNaresh更新回答:) – Alex

+0

非常感謝你的朋友 –

0

爲您稱爲parent(ParentComponent)和您稱爲child(ChildComponent)的一個單獨生成一個組件。然後,您可以設置一個路徑,將ParentComponent或ChildComponent加載到模板中的路由器插座中。這樣做,ParentComponent和ChildComponent處於相同的路由級別。你必須改變他們的名字纔有意義。

+0

謝謝你回答我。但它的嵌套組件夥伴 –

1

在父組件,注入活化路線如下所示:

class ParentComponent { 
    constructor(public route: ActivatedRoute) 
    } 
} 

現在您可以使用route上的children屬性來決定當前組件是否爲路由樹中的葉組件。連同ngIf,這可以被用來隱藏圖的一部分:

<div *ngIf="route.children.length === 0"> 
    Some content that should only be shown when the user is at the parent component itself. 
</div> 

<router-outlet></router-outlet> 

在上面的例子中,div將只如果用戶是父組件本身上示出,但如果用戶是在兒童組件上。