iCnoK
iCnoK

Reputation: 23

How to stay at the same page after page reload in Angular

Few days ago I have started learning Angular and tried to do a simple SPA. I have added 2 components and routing for them:

const appRoutes: Routes = [
  {path: 'main', component: MainPageComponent}, //default page
  {path: 'registration-form', component: RegistrationPageComponent}, //"another" page
  {path: 'login-form', component: LoginPageComponent},
  {path: '**', component: PageNotFoundComponent}
];

So I have default routing to main page and the button on it, which navigates to another page (component):

<button style="border-color: transparent;"  type="button"
        class="item7 btn btn-secondary btn-pill" [routerLink]="['/registration-form']">
   <i class="fa fa-sign-in mr-2"></i>
   {{logButtonTitle}}
</button>

When I click on this button, it successfully navigates me to another page (component), but if I press F5 on the other page (browser page reload) my application forgets my second page and loads the default one. So, I don't know how to stay on another page after page reloading and if can I do it at all.

P.s. - I tried to find any information about it, but all solutions that I found didn't help me.

Thanks!

Update: The code in app.components.ts

Here I load default page always when application starts:

import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  constructor(
    private router: Router
  ) {}

  ngOnInit(): void {
    this.router.navigate(['/main']);
  }
}

Upvotes: 2

Views: 19318

Answers (1)

ionut-t
ionut-t

Reputation: 1177

You are always redirected to your main route because you are specifying in your root component to navigate to the main route.

Everytime the app is reloaded its routing state is lost. So you should remove that from your root component. I don't understand why you're doing like that.

If you want the main route to be used by default, in your routing module add this:

const appRoutes: Routes = [
  // first line redirects to '/main' instead of '/'
  {path: '', redirectTo: 'main',
  {path: 'main', component: MainPageComponent}, //default page
  {path: 'registration-form', component: RegistrationPageComponent}, //"another" page
  {path: 'login-form', component: LoginPageComponent},
  {path: '**', component: PageNotFoundComponent}
];

Upvotes: 3

Related Questions