Title: Stop Child Navigation Angular router
Tags: angular
Question: 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 =&gt; {
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.
Comment: You shouldn't be loading your parent component if the page shouldn't be loaded. By that, I mean, you should be checking for your condition before actually loading the page (or navigating to the page).


Here is another answer: 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

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2018:00:05/22/18', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<angular>', 'Title': 'Stop Child Navigation Angular router', 'ViewCount': 427, 'id': 50473285, 'user_AboutMe': '<p>A good book to read <a href="http://www.fastchip.net/howcomputerswork/bookbpdf.pdf" rel="nofollow noreferrer">http://www.fastchip.net/howcomputerswork/bookbpdf.pdf</a></p>\n', 'user_AccountId': 1394983.0, 'user_DisplayName': 'Ara Yeressian', 'user_Reputation': 3286.0, 'user_Views': 166.0, 'user_id': 1324935.0}}