在angular 2中隐藏父视图

在angular 2中隐藏父视图,angular,Angular,我必须隐藏上面的父视图 下面是我的代码。当我点击任何一个框时,父对象应该是隐藏的子对象应该出现 <app-navbar></app-navbar> <div class="container" [style.height]='height' style="margin-top: 7%;"> <div class="row box_rpad"> <app-

我必须隐藏上面的父视图

下面是我的代码。当我点击任何一个框时,父对象应该是隐藏的子对象应该出现

        <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>


为您称之为父组件(ParentComponent)的组件和称之为子组件(ChildComponent)的组件制作单独的组件。然后,您可以设置一个路由,将ParentComponent或ChildComponent加载到模板中的路由器出口中。这样,ParentComponent和ChildComponent处于相同的路由级别。你必须改变他们的名字,这样才有意义。

以下内容应该可以做到这一点。。。。这个解决方案不是很理想,但至少它可以按您的需要工作。因此,只需使用布尔值将要隐藏在div中的内容包装起来,例如

<div *ngIf="notSelected">
  <!-- your code here -->
</div>
要告知从子项导航回父项时需要再次显示父项,您可以使用
主题
。因此,在你的父母声明一个主题:

public static showParent: Subject<any> = new Subject();
在您的孩子身上,在导航回家长之前,无论该事件是什么:

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

在父组件中,按如下方式注入激活的路由:

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
,但如果用户位于子组件上,则不会显示该div。

2021年1月

可以从父管线中删除零部件


谢谢你回答我。但是它是一个嵌套组件buddy您是否可以不使用父组件订阅的服务,并且子组件可以在单击时更新订阅“Hide”变量,或者反之亦然?我已经悬赏@Vikash Ratheeyahe其工作伙伴的答案。但在浏览完主页后就没有内容了。主页变为空白:(@IamNaresh更新答案:)不接受答案的原因是什么(这有什么问题吗?如果我刷新了父div无法隐藏的页面,为buddyhi buudy道歉这似乎是最简单的答案。惊人的答案:)真的谢谢!!:)这确实是正确的答案。谢谢你的回答。引用一位团队成员的话:“我很高兴我们不必重构代码的结构”@fundre听到这个消息我很高兴!
class ParentComponent {
  constructor(public route: ActivatedRoute)
  }
}
<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>
{
    path: 'parent',
    //component: ParentComponent,
    children: [
      { path : '', pathMatch:'full', component: ParentComponent},
      { path: 'child', component: ChildComponent },
    ],
  }