0

I'm new to Angular 2+ and I've not been able to resolve this issue with Routing.

So far I imported import { RouterModule, Routes } from '@angular/router'; in my app.module.ts file.

added RouterModule.forRoot(appRoutes) in imports section.

added private router: Router in my main component's constructor ( Main Component -> From which i want to rout to different component)

and added button and function to my main component's file to rout to different component :

test-list.component.html:

<table class="table table-dark table-hover">
    <thead>
        <tr>
            <th scope="col">First Name</th>
            <th scope="col">Last Name</th>
        </tr>
    </thead>
    <tbody *ngFor="let item of tests">
        <td>{{item.firstName}}</td>
        <td>{{item.lastName}}</td>
    </tbody>
</table>
<button routerLink="/home" class="btn btn-primary" (click)="goToForm()">Page Name</button>
<router-outlet></router-outlet>

test-list.component.ts:

import { Component, OnInit } from '@angular/core';
import { TestService } from 'src/app/services/test.service';
import { Test } from 'src/app/common/test';
import { Router } from '@angular/router'


@Component({
  selector: 'app-test-list',
  templateUrl: './test-list.component.html',
  styleUrls: ['./test-list.component.css']
})
export class TestListComponent implements OnInit {

  tests: Test[];

  constructor(private productService: TestService,private router: Router) { }

  ngOnInit() {
    this.getTests();
  }


  getTests(){
    this.productService.getList().subscribe(
      data => {
        this.tests = data;
        console.log(data);
      }
    );
  }

  goToForm(){
    this.router.navigate(['/home']);
  }

App Module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { TestService } from './services/test.service';
import { TestListComponent } from './components/product-list/test-list.component';
import { RouterModule, Routes } from '@angular/router';
import { SecondTestComponent } from './components/second-test-component/second-test.component';

    const appRoutes: Routes = [
  { path: 'home', component: SecondTestComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    TestListComponent,
    SecondTestComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [TestService],
  bootstrap: [AppComponent]
})
export class AppModule { }

second-test.component.html (I want to open this page on clicking the button):

<h1> HI ! </h1>

When I click the button it shows the contents of second component below the html code instead of opening the page of second component . (I want to entirely close the first component and open the second component's html)

1
  • I changed the routerLink to /home , nothing changed Commented Dec 16, 2019 at 12:58

1 Answer 1

1

For routing in Angular you need a routing-parent component which contains the router-outlet. This could be for example the app.component.ts.

Include the router-outlet in there where you want to display the content of the routes.

<router-outlet></router-outlet>

The routes are defined correctly although it only makes sense to have routes if you have more than one route. Currently you have defined the route /home to display the contents of the SecondTestComponent. If you target another route, no content will be displayed. Add another component you want to display instead of the SecondTestComponent on another route. Configure it equivalently to the home route.

From your component templates your can then navigate via the routerLink as you did in your first snippet. But this routerLink is targeting to the page /secondTest which you haven't configured (I guess you mean /home).

<button routerLink="/home">Navigate</button>

You do not need to handle the (click) event in addition to the routerLink attribute. General Hint: You can compose routes and for example route to an id if you hand in an array of path elements.

<button [routerLink]="['/books', id]"></button>
Sign up to request clarification or add additional context in comments.

6 Comments

So if i understand it correctly, If I want to rout from one component to another , I need a third component in which I'll place the <router-outlet> ?
Exactly. The router-outlet is the position in the DOM where the route-content is placed. For example you have the AppComponent where the router-outlet is placed. Then you have ComponentA and ComponentB configured with [{path: '/home': component: ComponentA}, {path: '/contact', component: ComponentB}]. Then it shows AppComponent with the content of ComponentA at the router-outlet position if the route is /home or the content of ComponentB if the route is /contact.
But you can also go to another route from the parent component. So if AppComponent has a routerLink attribute, that is valid, too.
Is there any other way of just clicking the button and opening another component html template instead of just creating parent-child components for routing ?
You can load components dynamically by creating Component Factories, create instances of these factories and insert them. But I would not recommend it. It is quite complex. If you want to go that way you can have a look in the docs angular.io/guide/dynamic-component-loader. Going with the router should very easy once you get familiar with it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.