Search code examples
angularif-statementconditional-statementsrouterangular-routing

how to check active child router from parent router or parent router against?


How to possible check Children Router Active Or Not, Show The status true or false in angular 4,
Now currently I'm use : /* @angular/cli: 1.4.4 node: 8.6.0 typescript: 2.3.4 @angular/router: 4.4.4 */

my Parent route is:

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

Parent component is :

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

Solution

  • Import your parent component.ts

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

    and life cycle hooks ngOnInit() And create Refarence Of ActivatedRoute

    constructor(private activeRouter:ActivatedRoute) {}
    

    And Write Some code in your ngOnInit functions here..

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

    Note: This code is working my app ( Thank You )