【问题标题】:Hide parent view in angular 2在角度2中隐藏父视图
【发布时间】:2017-02-09 06:11:48
【问题描述】:

我必须隐藏上面的父视图。

以下是我的代码。当我单击任何一个框时,父级应该隐藏子级应该出现。

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

【问题讨论】:

  • 能不能只使用父组件订阅的服务,子组件点击时可以更新订阅“隐藏”变量,反之亦然?
  • 我已经悬赏@Vikash Rathee 的答案

标签: angular


【解决方案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 只会在用户位于父组件本身时显示,但不会在用户位于子组件时显示。

【讨论】:

  • 这似乎是最简单的答案。
  • 惊人的答案:)
  • 真的非常感谢!! :)
【解决方案2】:

2021 年 1 月

您可以从父路由中移除组件。 See example here

{
    path: 'parent',
    //component: ParentComponent,
    children: [
      { path : '', pathMatch:'full', component: ParentComponent},
      { path: 'child', component: ChildComponent },
    ],
  }  

【讨论】:

  • 感谢您的回答。引用团队成员的话“我很高兴我们不必重构代码结构”
  • @fundagain 很高兴听到这个消息!
【解决方案3】:

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

【讨论】:

  • 感谢您回答我。但它是一个嵌套组件伙伴
【解决方案4】:

以下应该可以解决问题....这个解决方案不是那么理想,但至少它可以按您的意愿工作。因此,只需使用布尔值将要隐藏的内容包装在 div 中,例如

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

【讨论】:

  • 是的,它的工作伙伴。但是导航主页后没有内容。主页变成空白 :(
  • @IamNaresh 更新答案:)
  • 不接受答案的原因? :( 有什么问题吗?
  • 对不起那个朋友
  • 嗨,兄弟,如果我刷新父 div 无法隐藏的页面
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-01
  • 1970-01-01
  • 2015-07-13
相关资源
最近更新 更多