Search code examples
javascriptangularangular2-routingangular6

Back button creating multiple components on the same page


In my Angular 6 app, there are certain pages that do not respond appropriately when I click "back". The site will instead spawn multiple components, instead of redirecting the user back to the single component they just went to.

For the faulty components, I made the component.html page be one single line like such as:

// home-page.component.html home

and

// admin-page.component.html admin

And then the component.ts page is using default code as well.

On my app.component.html, I just have the following:

<router-outlet></router-outlet>

Now when I go on the home page (via <a routerLink="/admin">Admin></a>), I correctly see this (more or less)in my HTML when I inspect the site. And note this is just the RESULTING HTML that appears when I right click - view page source etc... I know my routing is setup correctly as this whole thing works in Google Chrome, but not in Firefox.

<html> <head>...</head> <body> <app-root> <router-outlet> <app-admin-page>admin</app-admin-page> </router-outlet> </app-root> </body> </html>

But when I now press "back", I see the below

<html> <head>...</head> <body> <app-root> <router-outlet> <app-home-page>home</app-home-page> <app-admin-page>admin</app-admin-page> </router-outlet> </app-root> </body> </html>

When I pressed "back", it should of DELETED the <app-admin-page>admin</app-admin-page> and just kept the new <app-home-page>home</app-home-page>, but it keeps both. I can then press "forward" and then it'll have 3 components. Any ideas what is going on here? Note that if I'm on the 'admin' page and click the 'home' link (which does a routerLink thing), it works correctly. It's just the back button messing up.


Solution

  • You are mixing child components and routing. For any particular component, you should use one or the other.

    There should be no components defined between the <router-outlet></router-outlet> tags.

    Notice in your code above:

              <router-outlet>
                  <app-admin-page>admin</app-admin-page>
              </router-outlet>
    

    So either display both components as child components like this:

          <app-root>
             <app-home-page>home</app-home-page>
             <app-admin-page>admin</app-admin-page>
          </app-root>
    

    This will show both components, one above the other.

    OR

    Use routing:

          <app-root>
              <router-outlet></router-outlet>
          </app-root>
    

    This will show one component at a time in this location. Use a route configuration to define which components to display in the router outlet.

    RouterModule.forRoot([
      { path: 'home', component: HomeComponent },
      { path: '', redirectTo: 'home', pathMatch: 'full' },
      { path: 'admin', component: AdminComponent }
    ]),