I am creating an application using angular5 and express 4.16. I have anchor tag on home page on click of which another component should be rendered (it should be redirected to that URL) but only URL changes.
Required code is below.
app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { TestComponent } from '../test/test.component';
const routes: Routes = [
{ path: '', redirectTo: '/', pathMatch: 'full' },
{ path: 'Test', component: TestComponent }
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
app.component.ts
import { Component } from '@angular/core';
// Import the DataService
import { DataService } from './data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// Define a users property to hold our user data
employees: Array<any>;
// Create an instance of the DataService through dependency injection
constructor(private _dataService: DataService) {
// Access the Data Service's getUsers() method we defined
this._dataService.getEmployees()
.subscribe(res => this.employees = res);
}
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import {TestComponent } from '../test/test.component';
import { AppRoutingModule } from './app-routing.module';
import{DataService} from './data.service'
import {HttpModule} from '@angular/http'
@NgModule({
imports: [
BrowserModule,
FormsModule,
AppRoutingModule,
HttpModule
],
declarations: [
AppComponent,
TestComponent
],
providers: [DataService],
bootstrap: [AppComponent]
})
export class AppModule { }
out put of folder through ng build /dist/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>IndexV3</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
<test-html></test-html>
<script type="text/javascript" src="inline.bundle.js"></script>
<script type="text/javascript" src="polyfills.bundle.js"></script>
<script type="text/javascript" src="styles.bundle.js"></script>
<script type="text/javascript" src="vendor.bundle.js"></script>
<script type="text/javascript" src="main.bundle.js"></script>
</body>
</html>
Node/Express server.js
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
// API file for interacting with MongoDB
const api = require('./server/routes/api');
// Parsers
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
// Angular DIST output folder
app.use(express.static(path.join(__dirname, 'dist')));
// API location
app.use('/api', api);
// Send all other requests to the Angular app
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
//Set Port
const port = process.env.PORT || '3000';
app.set('port', port);
const server = http.createServer(app);
server.listen(port, () => console.log(`Running on localhost:${port}`));
Output of home page as desired
Downoad screenshot Output after running localhost:3000 as desired anchor tag rendered
After click on anchor tag url changed but test component didnt rendered on browser
Downoad screenshot
test.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'test-html',
templateUrl: './test.component.html'
})
export class TestComponent {
title = 'app';
}
app.component.html
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
<h1>
</h1>
</div>
<a [routerLink]="['/Test']" >test</a>
<ul>
<li *ngFor="let employee of employees">{{employee.name}}</li>
</ul>
test.component.html
<span>yeeee</span>
Project Structure
download project structure if required
To use the router module in our main app file we first require() the route module (wiki. js). We then call use() on the Express application to add the Router to the middleware handling path, specifying a URL path of 'wiki'.
js server. The express. Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests. Multiple requests can be easily differentiated with the help of the Router() function in Express.
Add the AppRoutingModule link The router is dedicated to routing and imported by the root AppModule . By convention, the module class name is AppRoutingModule and it belongs in the app-routing.module.ts in the src/app directory. Run ng generate to create the application routing module.
At the basic level, routing allows angular to display different "pages" or components. You probably want to have it, if you want to navigate across pages in your application. It shouldn't hurt anything if you add it, but don't use it.
You are missing the router-outlet. Take the template you have for app.component and create a new component with that template. Then make your app.component.html contain only
<router-outlet></router-outlet>
Then in your app.routing.module.ts replace the object for your home route with:
{ path: '', component: YourNewHomeComponent
},
more about router-outlet: https://angular.io/guide/router#router-outlet
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