I have an Angular 6 application. At first it was just one page (let's say "search page"), so I put the page content in app.component.html and related functions, etc. to the app.component.ts. So the search page is in appcomponent. Now I was asked to add another page (Login page). So, now the first page that needs to be opened when the page is first loaded is login page. If the login is successful, then "search page" should open.
I am new to Angular so I look at some routing & navigation tutorials and applied what they are doing. The problem is that now when the page is first loaded it opens both LoginComponent and AppComponent (search page) together. At the top of the page login screen and under that search screen. Also, if I go to "/search" then this time there is two search pages one under the other.
So I have one extra search page.I get that the problem is that the search page is being in appcomponent. I guess that the app loads this component by default. What I want is that I want to display LoginComponent first (when the page is first loaded), if the login is successful, navigate to search page.
Here is what I have done to add routing:
I added import {RouterModule} from '@angular/router';
to my app.module.ts
Also I added RouterModule in imports like this (again in app.module.ts)
imports: [
RouterModule.forRoot([
{path: '', component: LoginComponent},
{path: 'search', component:AppComponent}
])
],
Added <router-outlet></router-outlet>
in app.component.html. This HTML file included my search page content like navbar, table etc. And at the beginning of it I put router line (I know it is wrong to put inside my search page but In the tutorial I watched, he put <router-outlet></router-outlet>
in app.component.html. I guess that the reason for my double pages is this HTML file but could not get it to work somewhere else.)
In login.component.html, Login page content and of course a Login button with (click)="onLogin()"
login.component.ts includes onLogin function if the login is successful this.router.navigate(['/search']);
Finally in my index.html I call the appcomponent inside body <app-root></app-root>
Right now navigation with login works but as I said the initial page with URL: "http://localhost:4200/" includes both login and search page. Also URL: "http://localhost:4200/search" includes two search pages.
Just create a new component for search
and remove it from app
component, then change your route module to
RouterModule.forRoot([
{ path: '', component: LoginComponent },
{ path: 'search', component: SearchComponent },
])
And make sure that in app.component.html
, only <router-outlet></router-outlet>
exists
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With