Ara Yeressian
Ara Yeressian

Reputation: 4045

Stop Child Navigation Angular router

I have a router which has child router. The parent router has a component. In that component I check for a condition and if it fails I redirect. The problem is the child router component ngOnInit code gets executed. Is there any way to prevent that.

const routes: Routes = [    
  {
      path: 'parent/:id',
      component: ParentComponent,
      children: [
          {
              path: 'child',
              component: ChildComponent
          }
      ]
  }
];

class ParentComponent implements OnInit {
  readonly NUMBER_REGEX = /^\+?\d+$/;
  ngOnInit() {
    this.route.params.subscribe( params => {
      if (params.id) {
          if (!this.NUMBER_REGEX.test(params.id)) {
              this.router.navigateByUrl('/not-found');              
          }
      }   
    });
  }
}

class ChildComponent implements OnInit {
  ngOnInit() {
    console.log('don\'t want this to work on /parent/string/child but still works');
  }
}

I know I can use services to pass data between components. But I want cleaner solution.

Upvotes: 0

Views: 875

Answers (1)

Antoniossss
Antoniossss

Reputation: 32507

Yes, use RouteGuard to prevent from routing if some conditions are met (or not)

RouteGuards are exactly for this purpose

https://angular.io/guide/router#milestone-5-route-guards

Upvotes: 1

Related Questions