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

Md.*_*yed 5 router if-statement conditional-statements angular-routing angular

如何可能检查子路由器是否活动,在 angular 4 中显示状态真或假,
现在我使用:/* @angular/cli: 1.4.4 node: 8.6.0 typescript: 2.3.4 @angular/路由器: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
            }
        ]
    }
]
Run Code Online (Sandbox Code Playgroud)

父组件是:

export class SummaryOfFindingsComponent implements OnInit {
    isUserSelected;
    constructor() { this.isUserSelected=false; }
    ngOnInit() { }
    isUserItemSelect(){
        this.isUserSelected=true;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jef*_*nes 7

这是一种在 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))
Run Code Online (Sandbox Code Playgroud)


小智 6

导入你的父 component.ts

import { ActivatedRoute } from '@angular/router';
Run Code Online (Sandbox Code Playgroud)

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

constructor(private activeRouter:ActivatedRoute) {}
Run Code Online (Sandbox Code Playgroud)

并在您的 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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 这仅适用于第一次加载父组件,但我需要在此页面中更改任何路由器 (2认同)