Search code examples
angularangular2-routingrouter-outlet

Navigation in home page is not working in angular 2


I have navigated from login page to home page.In home page,if i click questions,questionsnew or what ever link the corresponding page is not showing inside the home page(http://localhost/home).

Here is my all code snippets

app.module.ts

var myroutes:Routes=[
{path:"",redirectTo:"home",pathMatch:"full"},
{path:"home",component:HomeComponent},
{path: 'userdetails',component:UserdetailsComponent},
{path:'questions',component:QuestionsIndexComponent},
{path:'questionsnew',component:QuestionsNewComponent  },
{path:'questionsview',component:QuestionsViewComponent},
{path:'FancyButtons',component:FancybuttonsComponent}];
var allroutes=RouterModule.forRoot(myroutes);

index.html

<body>
  <app-root></app-root>
</body>

app.component.html

<div id="appdesign" align="center" *ngIf="showButton">
  <br>
  <br><br><br><br><br><br>
  <h1>MY FIRST PROJECT IN ANGULAR2</h1>
  <br><br><br><br><br><br><br><br>

 <h4>Existing Users can: </h4>
  <button style="height: 25px;width:50px" routerLink="/login" (click)="btnloginclick()">Login</button>
  <br><br><br><br><br>
  <h4>New User can:</h4>     
<button style="height: 25px;width:50px" routerLink="/register">Register</button>
</div>    
 <router-outlet></router-outlet>

login.component.html

<div id="logindiv">
  <h4>Login</h4>
<form #myloginform="ngForm">
Email : <input type="text"[(ngModel)]="email" required="required" #ctrlemail="ngModel"  name="email" ><br>
<span class="error" *ngIf="ctrlemail.invalid && ctrlemail.touched && ctrlemail.errors.required">EMAIL CANT BE BLANK</span>
Password: <input type="password" [(ngModel)]="password" name="password"  ><br>
<input type="submit" value="Login" (click)="onLoginClick(myloginform)"><br>
  {‌{message}}
</form>
</div>

login.component.ts

onLoginClick(myloginform)
{
if (myloginform.valid==true)
{
    this.objroute.navigate(['home']);
}

Home.component.html

<div id="header">
  <br>
<a routerLink="userdetails" routerLinkActive="active">UserDetails</a>&nbsp;    
  <a routerLink="questions">Questions</a>&nbsp;
  <a routerLink="questionsnew">New Question</a>&nbsp;
  <a routerLink="questionsview">View Question</a>&nbsp;
  <a routerLink="FancyButtons">Fancy Buttons</a>
  <br>
</div>

<div id="pagecontent">
  <router-outlet></router-outlet>
</div>

<div id="footer">
</div>

Please identify my issue and provide me correct solution,so that i could proceed with my sample project.

Thanks

Rajula


Solution

  • it is because the url you are trying to navigate to does not exist try it like this

    <a routerLink="../questions">Questions</a>&nbsp;
      <a routerLink="../questionsnew">New Question</a>&nbsp;
      <a routerLink="../questionsview">View Question</a>&nbsp;
      <a routerLink="../FancyButtons">Fancy Buttons</a>