如何从父路由器或父路由器检查活动子路由器?

时间:2017-10-13 04:53:57

标签: angular if-statement conditional-statements router angular-routing

如何检查儿童路由器是否有效,显示角度4中的状态为true或false,
 现在我正在使用:     / *     @ angular / cli:1.4.4     节点:8.6.0     打字稿:2.3.4     @ angular / router:4.4.4 * /

我的父路线是:

const routes:Routes=[
    {
        path: '', component: SummaryOfFindingsComponent,
        children:[
            {
                path:'data-time-frame', component: DataTimeFrameComponent
            },
            {
                path:'email-address', component: EmailAddressesComponent
            },
            {
                path:'repair-orders', component: RepairOrdersComponent
            },
            {
                path:'total-records', component:TotalRecordsComponent
            },
            {
                path:'unique-households', component: UniqueHouseholdsComponent
            },
            {
                path:'unique-vins', component: UniqueVinsComponent
            }
        ]
    }
]

父组件是:

export class SummaryOfFindingsComponent implements OnInit {
    isUserSelected;
    constructor() { this.isUserSelected=false; }
    ngOnInit() { }
    isUserItemSelect(){
        this.isUserSelected=true;
    }
}

2 个答案:

答案 0 :(得分:2)

导入您的父组件.ts

import { ActivatedRoute } from '@angular/router';

和生命周期挂钩ngOnInit()并创建ActivatedRoute的Refarence

constructor(private activeRouter:ActivatedRoute) {}

并在此处写入ngOnInit函数中的一些代码..

ngOnInit() {
    var _activeChild = this.activeRouter.children.length;
    if (_activeChild!=0) {
        //your active children 1 or more than children then active 1,otherwise it is 0
    }
}

注意:此代码正在运行我的应用程序(谢谢)

答案 1 :(得分:1)

这是一种观察Observable中儿童的方法......

this.router.events.pipe(
  filter(event => event instanceof ActivationEnd),
  filter(event => (event as ActivationEnd).snapshot.component === SearchFeatureComponent),
  map(event => (event as ActivationEnd).snapshot.children.length),
  distinctUntilChanged()
).subscribe(children => console.warn('route children', children))