简体   繁体   中英

Angular - URL changed but view not loaded

This is my app-routing-module.ts

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

I've written a function to check if the URL is working with a static value in parent.component.ts .

goToChild() {
   this.router.navigate(['1/john'], { relativeTo: this.route });
}

And I call the function in the parent.component.html .

<button class="btn btn-primary" (click)="goToChild()">Search</button>

When I click the button, I get the correct URL in the address bar,

 localhost:3000/parent/1/john

But the view never loads, it stays on the parent.component.html . I'm fairly new to Angular and I'm using version 5.

And if I have my routes like this, it works fine.

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

It feels more appropriate for me to put the ChildComponent route under children array of the ParentComponent , but when I do it. Only the URL changes, not the view.

Any help will be much appreciated.

You need to add a <router-outlet></router-outlet> inside the template. That's how you allow child navigation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM