Angular 6 [(ngModel)] in view not changing variable in component - data-binding

I have a ClientModule module separate from the main AppModule.
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { ClientsRoutingModule } from './clients-routing.module';
import { ClientsListComponent } from './clients-list/clients-list.component';
import { ClientAddComponent } from './client-add/client-add.component';
import { ClientDetailComponent } from './client-detail/client-detail.component';
#NgModule({
imports: [
CommonModule,
ClientsRoutingModule
],
declarations: [ClientsListComponent, ClientAddComponent, ClientDetailComponent]
})
export class ClientsModule { }
I have FormsModule imported on AppModule
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
I am trying to bind input fields from view to the following component:
import { Component, OnInit, Input } from '#angular/core';
import { ClientModel } from '../client.model';
#Component({
selector: 'app-client-add',
templateUrl: './client-add.component.html',
styleUrls: ['./client-add.component.scss']
})
export class ClientAddComponent implements OnInit {
fname: string;
lname: string;
constructor() { }
ngOnInit() {
}
createClient() {
console.log(this.fname, this.lname);
}
}
And following is my view
<div class="card-body">
<form class="form">
<div class="form-group">
<label for="">First Name {{fname}}</label>
<input type="text" ([ngModel]) = "fname" class="form-control rounded-0" required>
</div>
<div class="form-group">
<label for="">Last Name</label>
<input type="text" ([ngModel]) = "lname" class="form-control rounded-0">
</div>
<button type="button" (click)="createClient()" class="btn btn-success float-center">Create New Client</button>
</form>
</div>
When I click the Create New Client button, the resultant log is undefined undefined
What am I doing wrong? I have spent a lot of time tackling this issue/bug in my code but so far its no good. Please help.
And this may be unrelated but I followed angular.io guide on lazy-loading of modules, where it mentions I should see an incoming chunk file while lazy-loading is happening in network tab but I don't. Maybe it has something to do with it?
EDIT
I also tried importing FormsModule in in ClientsModule. Problem persists.
EDIT
However, [(ngModel)] works as expected in app.component.ts of AppModule.

My bad.
In my view ngModel should be a banana in the box [(ngModel)] but I mistyped as a box in the banana ([]).

Related

Routing edit/id in asp.net core application with angular not working

I am learning building application using angular and asp.net core using these videos on this link. Everything works fine except the edit of a component. If I give a URL like below, it goes to the route for error in app-routing.module.ts even though there's no error in the browser console log.
http://localhost:4200/genres/edit/1
The app-routing.model.ts is as below
import { Component, NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { CreateActorComponent } from './actors/create-actor/create-actor.component';
import { EditActorComponent } from './actors/edit-actor/edit-actor.component';
import { IndexActorsComponent } from './actors/index-actors/index-actors.component';
import { CreateGenreComponent } from './genres/create-genre/create-genre.component';
import { EditGenreComponent } from './genres/edit-genre/edit-genre.component';
import { IndexGenresComponent } from './genres/index-genres/index-genres.component';
import { HomeComponent } from './home/home.component';
import { CreateMovieTheaterComponent } from './movie-theaters/create-movie-theater/create-movie-theater.component';
import { EditMovieTheaterComponent } from './movie-theaters/edit-movie-theater/edit-movie-theater.component';
import { IndexMovieTheaterComponent } from './movie-theaters/index-movie-theater/index-movie-theater.component';
import { CreateMovieComponent } from './movies/create-movie/create-movie.component';
import { EditMovieComponent } from './movies/edit-movie/edit-movie.component';
const routes: Routes = [
{path:' ', component:HomeComponent},
{path:'genres', component:IndexGenresComponent},
{path:'genres/create', component:CreateGenreComponent},
{path:'genres/edit:id', component:EditGenreComponent},
{path:'actors', component:IndexActorsComponent},
{path:'actors/create', component:CreateActorComponent},
{path:'actors/edit:id', component:EditActorComponent},
{path:'movietheaters', component:IndexMovieTheaterComponent},
{path:'movietheaters/create', component:CreateMovieTheaterComponent},
{path:'movietheaters/edit:id', component:EditMovieTheaterComponent},
{path:'movies/create', component:CreateMovieComponent},
{path:'movies/edit:id', component:EditMovieComponent},
// {path:'**',component:HomeComponent}
{path:'**',redirectTo:' '}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
edit-genre.component.ts is
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { genreCreationDTO } from '../genres.model';
#Component({
selector: 'app-edit-genre',
templateUrl: './edit-genre.component.html',
styleUrls: ['./edit-genre.component.css']
})
export class EditGenreComponent implements OnInit {
constructor(private activatedRoute:ActivatedRoute) { }
model: genreCreationDTO={name:"Drama"};
ngOnInit(): void {
this.activatedRoute.params.subscribe(params=>{
});
}
//Event emiited value passed from child form-genre-creation to parent create-genre.component
//to be displayed
saveChanges(genreCreationDTO:genreCreationDTO)
{
}
}
edit-genre.component.html is
<h2>Edit Genre</h2>
<app-form-genre [model]="model" (onSaveChanges)="saveChanges($event)"></app-form-genre>
form-genre.component.html is
<form (submit)="saveChanges()" [formGroup]="form">
<mat-form-field appearance="outline">
<mat-label>Name*</mat-label>
<input matInput formControlName="name">
<mat-error *ngIf="form.invalid">{{getErrorMessageFieldName()}}</mat-error>
</mat-form-field>
<div>
<button mat-flat-button color="primary" [disabled]="form.invalid">Save Changes</button>
<a mat-stroked-button routerLink="/genres">Cancel</a>
</div>
form-genre.component.ts is
import { Component, OnInit, Output,EventEmitter, Input } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { Router } from '#angular/router';
import { firstLetterUppercase } from 'src/app/validators/firstLetterUppercase';
import { genreCreationDTO } from '../genres.model';
#Component({
selector: 'app-form-genre',
templateUrl: './form-genre.component.html',
styleUrls: ['./form-genre.component.css']
})
export class FormGenreComponent implements OnInit {
constructor(private router: Router, private formBuilder:FormBuilder) { }
#Input()
model!: genreCreationDTO;
//Event Emitter
#Output()
onSaveChanges: EventEmitter<genreCreationDTO>=new EventEmitter<genreCreationDTO>();
form!: FormGroup;
ngOnInit(): void {
this.form= this.formBuilder.group({
name:['',[Validators.required, Validators.minLength(3),firstLetterUppercase()]]
});
if(this.model!==undefined){
this.form.patchValue(this.model);
}
}
getErrorMessageFieldName()
{
const field= this.form.get("name");
if(field?.hasError("required"))
{
return "The name field is required";
}
if(field?.hasError("minLength")){
return "The minimum length is 3"
}
if(field?.hasError('firstLetterUppercase')){
return field.getError('firstLetterUppercase').message;
}
return '';
}
saveChanges()
{
//Emit value from child form-genre.compnent to parent create-genre.component
this.onSaveChanges.emit(this.form.value);
// this.router.navigate(['/genres']);
}
}
I am new to .net core framework & angular and i'm using forms(chapter sharing forms) in the video tutorial by Felipe galivan. Everytime I give an edit/id url for a component, it keeps using this
{path:'**',redirectTo:' '}
in the app-routing.module.ts as if say genres/edit/id has no match. I'm doing exactly as Felipe in the video, mine keeps redirecting me to home page instead of genres/edit. Why is this happening?

JWT Module can't compile

After adding a few lines of code I described below appears
I have a problem, when I try to compile Angular, I have this error:
ERROR in node_modules/#auth0/angular-jwt/index.d.ts:29:48 - error NG6005: JwtModule.forRoot returns a ModuleWithProviders type without a generic type argument. Please add a generic type argument to the ModuleWithProviders type. If this occurrence is in library code you don't control, please contact the library authors.
29 static forRoot(options: JwtModuleOptions): ModuleWithProviders;
~~~~~~~~~~~~~~~~~~~
src/app/app.component.html:9:1 - error NG8001: 'app-nav' is not a known element:
1. If 'app-nav' is an Angular component, then verify that it is part of this module.
2. If 'app-nav' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '#NgModule.schemas' of this component to suppress this message.
9 <app-nav></app-nav>
~~~~~~~~~~~~~~~~~~~
src/app/app.component.ts:8:16
8 templateUrl: './app.component.html',
~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component AppComponent.
src/app/app.component.html:10:1 - error NG8001: 'router-outlet' is not a known element:
1. If 'router-outlet' is an Angular component, then verify that it is part of this module.
2. If 'router-outlet' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '#NgModule.schemas' of this component to suppress this message.
10 <router-outlet></router-outlet>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/app/app.component.ts:8:16
8 templateUrl: './app.component.html',
~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component AppComponent.
src/app/nav/nav.component.html:3:33 - error NG8002: Can't bind to 'routerLink' since it isn't a known property of 'a'.
3 <a class="navbar-brand" [routerLink]="['/home']">Dating App</a>
~~~~~~~~~~~~~~~~~~~~~~~~
src/app/nav/nav.component.ts:8:16
8 templateUrl: './nav.component.html',
~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component NavComponent.
src/app/register/register.component.html:6:74 - error NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'.
6 <input type="text" class="form-control" required name="username" [(ngModel)]="model.username" placeholder="Username">
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/app/register/register.component.ts:8:16
8 templateUrl: './register.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component RegisterComponent.
src/app/register/register.component.html:11:78 - error NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'.
11 <input type="password" class="form-control" required name="password" [(ngModel)]="model.password" placeholder="Password">
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/app/register/register.component.ts:8:16
8 templateUrl: './register.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component RegisterComponent.
src/app/register/register.component.html:1:22 - error NG8003: No directive found with exportAs 'ngForm'.
1 <form #registerForm="ngForm" (ngSubmit)="register()">
~~~~~~
src/app/register/register.component.ts:8:16
8 templateUrl: './register.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component RegisterComponent.
this i my index.d.ts
import { ModuleWithProviders, Provider } from '#angular/core';
export * from './src/jwt.interceptor';
export * from './src/jwthelper.service';
export * from './src/jwtoptions.token';
export interface JwtModuleOptions {
jwtOptionsProvider?: Provider;
config?: {
tokenGetter?: () => string | null | Promise<string | null>;
headerName?: string;
authScheme?: string;
whitelistedDomains?: Array<string | RegExp>;
blacklistedRoutes?: Array<string | RegExp>;
throwNoTokenError?: boolean;
skipWhenExpired?: boolean;
};
}
declare module "#angular/core" {
interface ModuleWithProviders<T = any> {
ngModule: Type<T>;
providers?: Provider[];
}
}
export declare class JwtModule {
constructor(parentModule: JwtModule);
static forRoot(options: JwtModuleOptions): ModuleWithProviders;
}
//# sourceMappingURL=index.d.ts.map
this is my app.module.ts:
import { MemberCardComponent } from './members/member-card/member-card.component';
import { appRoutes } from './routes';
import { ErrorInterceptorProvider } from './_services/error.interceptor';
import { AuthService } from './_services/auth.service';
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import {HttpClientModule} from '#angular/common/http';
import {FormsModule, } from '#angular/forms';
import { BsDropdownModule } from 'ngx-bootstrap/dropdown';
import { RouterModule } from '#angular/router';
import { JwtModule } from '#auth0/angular-jwt';
import { AppComponent } from './app.component';
import { NavComponent } from './nav/nav.component';
import { RegisterComponent } from './register/register.component';
import { HomeComponent } from './home/home.component';
import { MemberListComponent } from './members/member-list/member-list.component';
import { ListsComponent } from './lists/lists.component';
import { MessagesComponent } from './messages/messages.component';
// tslint:disable-next-line:typedef
export function tokenGetter(){
return localStorage.getItem('token');
}
#NgModule({
declarations: [
AppComponent,
NavComponent,
RegisterComponent,
HomeComponent,
MemberListComponent,
ListsComponent,
MessagesComponent,
MemberCardComponent
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule,
BsDropdownModule.forRoot(),
RouterModule.forRoot(appRoutes),
JwtModule.forRoot({
config: {
// tslint:disable-next-line:object-literal-shorthand
tokenGetter: tokenGetter,
whitelistedDomains: ['localhost:5000'],
blacklistedRoutes: ['localhost:5000/api/auth']
}
}),
],
providers: [
AuthService,
ErrorInterceptorProvider
],
bootstrap: [
AppComponent
]
})
export class AppModule { }
Tt only adds that to app.module.ts:
// tslint:disable-next-line:typedef
export function tokenGetter(){
return localStorage.getItem('token');
}
and
JwtModule.forRoot({
config: {
// tslint:disable-next-line:object-literal-shorthand
tokenGetter: tokenGetter,
whitelistedDomains: ['localhost:5000'],
blacklistedRoutes: ['localhost:5000/api/auth']
}
}),
As I add this JWT module and try to add it to the project file I can't compile it if the problem is with the Angular version or it's something else.
I can't compile my program, How can I solve this problem.;/

Routing through links in Angular2

I am new in Angular 2 and I am still in learning phase, but I stuck in a problem and not getting the solution to it. Please help.
I have made a view of a login, then a link to it after clicking the link it will redirect to home then clicking a link there it will redirect to some other view.
Below is my code structure:
app.routing.ts:
import { Routes } from '#angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { UsersComponent } from './users/usercomponent';
export const routes: Routes = [
{ path: 'Home', component: HomeComponent },
{ path: 'Login', component: LoginComponent },
{ path: 'User', component: UsersComponent },
];
app.module.ts:
import { FormsModule } from '#angular/forms';
import { routes } from './app.routing';
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';
import { UsersComponent } from './users/usercomponent';
#NgModule({
imports: [BrowserModule, FormsModule, RouterModule.forRoot(routes)],
declarations: [AppComponent, LoginComponent, HomeComponent, UsersComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts:
import { Component } from '#angular/core';
import { OnInit } from '#angular/core';
#Component({
selector: 'app-initializer',
templateUrl: './app.component.html'
})
export class AppComponent {
title = 'Some NAme'
}
app.component.html:
<a routerLink="Login">Login</a>
<br />
<div>
<router-outlet></router-outlet>
</div>
login.component.ts:
import { Component } from '#angular/core';
#Component({
selector: 'login',
template: `
<h1><a routerLink="Home">Home</a>
<a routerLink="User">Users</a></h1>
<div>
<router-outlet></router-outlet>
</div>
`
})
export class LoginComponent {
constructor() {
}
}
The first page is working but after clicking home it is giving an error:
Cannot match any routes. URL Segment: 'Login/Home
I know that the link will be like / login, /home etc not like /login/home but how to implement it as I am not getting the solution for it and I am completely new to it.
Instead of giving only <h1><a routerLink="Home">Home</a>
you need to add / before the link like <h1><a routerLink="/Home">Home</a>.

Error while configuring routes in Angular 2

i have been working with a product list Project and while configuring routes to navigate between different views, I get a red squiggly under the '#Routes' decorator and when i hover over the Routes, it says 'Routes only refers to a type, but is being used as a value here'. I researched in so many sights including here and tried many different ways to resolve this but I could not find out the issue.
app.component.ts
import { Component } from '#angular/core';
import { ProductListComponent } from './products/product-list.Component';
import { ProductService } from './products/product.service'
import { Routes } from '#angular/router';
import 'rxjs/Rx'; // Load all features
import { WelcomeComponent } from './home/welcome.component'
#Component({
selector: 'pm-app',
template: `
<div>
<nav class='navbar navbar-default'>
<div class='container-fluid'>
<a class='navbar-brand'>{{pageTitle}}</a>
<ul class='nav navbar-nav'>
<li><a>Home</a></li>
<li><a>Product List</a></li>
</ul>
</div>
</nav>
</div>
` ,
entryComponents : [ProductListComponent],
providers: [ProductService]
})
#Routes([
{ path: '/welcome' , name: 'Welcome' , component: WelcomeComponent, useAsDefault: true},
{ path: '/products' , name: 'Products' , component: ProductListComponent }
])
export class AppComponent {
pageTitle:string = 'Acme Product Management';
}
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { ProductListComponent } from './products/product-list.Component';
import { HttpModule } from "#angular/http";
import { RouterModule } from '#angular/router'
import { ProductFilterPipe } from './products/product-filter.pipe';
import { StarComponent } from './shared/star.component';
import { AppComponent } from './app.component';
#NgModule({
imports: [ BrowserModule,FormsModule,HttpModule,RouterModule],
declarations: [ AppComponent,ProductListComponent,ProductFilterPipe,StarComponent],
bootstrap: [ AppComponent ]
})
export class AppModule { }
welcome.compnent.ts
import { Component } from '#angular/core';
#Component({
templateUrl: 'app/home/welcome.component.html'
})
export class WelcomeComponent {
public pageTitle: string = 'Welcome';
}
I think my coding is fine. But unable to get the expected result. Please Help!
Found out, the issue is... with RC5, Routes is an array of path's & is no more a Decorator, and you have to import 'RouterModule' instead of 'provideRouter'. While exporting you have to use 'RouterModule.forRoot'.
Also with RC5, we no longer specify the string name of the component while configuring routes instead we only specify the path & component only. And we no longer use the prefix '/' for the path. Also we no longer using useAsDefault instead we use redirectTo property to configure the default path.
I have used a separate module to do my route configurations instead of doing it in the root component as earlier. An updated version of my route configuration is given as below. Hope this will be helpful.
app.routes.ts
import { Routes, RouterModule } from '#angular/router';
import { ProductListComponent } from './products/product-list.Component';
import { WelcomeComponent } from './home/welcome.component'
import { ProductDetailComponent } from './products/product- detail.component';
const routes: Routes = [
{
path: 'welcome' ,
component: WelcomeComponent,
},
{
path: 'products' ,
component: ProductListComponent
},
{
path: 'product/:id' ,
component: ProductDetailComponent
},
{
path:'',
redirectTo:'/welcome',
pathMatch:'full'
},
];
export const routing = RouterModule.forRoot(routes);

Refreshing the angular 2 application is generating Error 404 - Page not found exception

I am developing Angular 2 application that is using KendoUI datagrid in asp.net web application. I have set index.html as the startup page. When i press F5, index.html loads. Click on the Risks Menu displays the datagrid with data that is defined in risk-list.component.html page. Its URL is localhost/risks. If I press F5, I get 404 page not found error. Could somebody tell me what the problem could be and how can I fix it?
This is my code:
risk-list.Component.ts
import { Component, OnInit } from '#angular/core';
import { Risk } from './risk';
import { RiskService } from './risk.service';
#Component({
moduleId: module.id,
selector: 'rm-risks',
templateUrl: '/app/risk-list.component.html',
providers: [RiskService]
})
export class RiskListComponent implements OnInit {
title = 'Risk List';
risks: Risk[];
constructor(private _riskService: RiskService) {
console.log(this.risks);
}
getRisks(): void {
this._riskService.getRisks().then(risks => this.risks = risks);
}
ngOnInit(): void {
this.getRisks();
}
};
risk-list.component.html
<kendo-grid [data]="risks">
<kendo-grid-column field="reference" title="Reference" width="120">
</kendo-grid-column>
<kendo-grid-column field="insuredName" title="Insured Name">
</kendo-grid-column>
<kendo-grid-column field="inceptionDate" title="Inception Date" width="230">
</kendo-grid-column>
<kendo-grid-column field="riskType" title="Risk Type" width="120">
</kendo-grid-column>
<kendo-grid-column field="Status" title="Status">
</kendo-grid-column>
<kendo-grid-column field="grossPremium" title="Gross Premium" width="230">
</kendo-grid-column>
<kendo-grid-column field="allocatedTo" title="Allocated To" width="120">
</kendo-grid-column>
<kendo-grid-column field="allocatedCompany" title="Allocated Company">
</kendo-grid-column>
<kendo-grid-column field="Discontinued" width="120">
<template kendoCellTemplate let-dataItem>
<input type="checkbox" [checked]="dataItem.Discontinued" disabled />
</template>
</kendo-grid-column>
</kendo-grid>
risk.service.ts
import { Injectable } from '#angular/core';
import { Risk } from './risk';
import { Risks } from './mock-risk';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/from';
#Injectable()
export class RiskService {
getRisks(): Promise<Risk[]> {
return Promise.resolve(Risks);
}
}
risk.ts
export class Risk {
riskId: number;
reference: string;
insuredName: string;
inceptionDate: string;
riskType: string;
status: string;
grossPremium: number;
allocatedTo: string;
allocatedCompany: string;
}
mock-risk.ts
import { Risk } from './risk'
export const Risks: Risk[] = [
{
"riskId": 1,
"reference": "HISC9308336",
"insuredName": "SA 84161",
"inceptionDate": "March 19, 2016",
"riskType": "Quote",
"status": "Indication",
"grossPremium": 100,
"allocatedTo": "Broker User",
"allocatedCompany": "Broker"
},
{
riskId: 2,
reference: "HISC9308337",
insuredName: "SA 84161",
inceptionDate: 'April 22, 2016',
riskType: 'Quote',
status: 'Indication',
grossPremium: 300,
allocatedTo: 'Broker User',
allocatedCompany: 'Broker'
}
];
risks.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { RiskListComponent } from './risk-list.component';
import { RiskService } from './risk.service';
import { RiskRoutingModule } from './risks-routing.module';
import { GridModule } from '#progress/kendo-angular-grid';
#NgModule({
imports: [
CommonModule,
FormsModule,
RiskRoutingModule,
GridModule
],
declarations: [
RiskListComponent
],
providers: [
RiskService
]
})
export class RisksModule { }
risks-routing.module.ts
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { RiskListComponent } from './risk-list.component';
#NgModule({
imports: [
RouterModule.forChild([
{ path: 'risks', component: RiskListComponent }
])
],
exports: [
RouterModule
]
})
export class RiskRoutingModule { }
app.component.html
<h1>Angular Router</h1>
<nav>
<a routerLink="/risks" routerLinkActive="active">Risks</a>
</nav>
<router-outlet></router-outlet>
app.component.ts
import { Component } from '#angular/core';
#Component({
moduleId: module.id,
selector: 'my-app',
templateUrl:'/app/app.component.html'
})
export class AppComponent { }
app-routing.module.ts
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { RiskListComponent } from './risk-list.component'
import { HomeComponent } from './home.component'
#NgModule({
imports: [
RouterModule.forRoot([
{ path: '', component: HomeComponent }
])
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
main.ts
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
This problem is solved by implementing HashLocationStrategy which adds # to all your routes. For example, http://localhost/myComponent becomes http://localhost/#/myComponent. You achieve this by adding HashLocationStrategy to AppModule's providers:
{ provide: LocationStrategy, useClass: HashLocationStrategy }
Of course, you need to import LocationStrategy and HashLocationStrategy from #angular/common:
import { LocationStrategy, HashLocationStrategy } from '#angular/common';
For more information, check Angular 2 Router & Navigation - Browser URL Styles.
When the browser is refreshed it will send a get request to the server with the current url, since angular is using HTML 5 style navigation, the url will make no sense to the server. Either update your server to serve the index.html on particular paths or use the HashLocationStrategy.
The benefit of using HTML 5 style navigation is that you can mix your angular app with server rendered pages.
An example of getting this working with asp.net: http://blog.johnnyreilly.com/2015/05/a-tale-of-angular-html5mode-aspnet-mvc.html
More reading on angular: https://angular.io/docs/ts/latest/guide/router.html#!#browser-url-styles
The best way to get rid of this Error404 page not found, you should import HashLocationStrategy to appModule.ts
When I previously worked on Angular, Same type of error raised in my Project, so that I created a simple repository for this kind of error (404 Page Not Found), it may help you. Here is the link -> AngularAppExample

Resources