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)
/home, nothing changed