Angular 5 - Unable to navigate from one component to another component - javascript

I'm developing Angular application. In that I've two pages login and home. After login submit button it should navigate to home page. For this I tried multiple ways but it is not navigating to home page. Finally I used <router-outlet></router-outlet> in my login(app.component.html) file. So home page is displaying in login page. I want to navigate home page after login. Below is my current output and code
And when I'm refreshing http://localhost:4200/home it is showing errorlike below
app.component.html (login page)
<div align="center">
<form (ngSubmit)="onLoginSubmit()" class="fullForm">
<div class="imgcontainer"></div>
<h2>PL Auth</h2>
<div class="container">
<form (ngSubmit)="generateOtpSubmit()" class="generateOtpForm">
<label> <b>Username: </b>
</label> <input type="text" placeholder="Enter Username" id="username"
[(ngModel)]=userName name="uname" required> <br> <br>
<label> <b>Password : </b>
</label> <input type="password" placeholder="Enter Password" id="password"
[(ngModel)]=password name="psw" required> <br> <br>
<button type="submit" class="otpButton">Generate OTP</button>
</form>
<br> <br> <label> <b>Enter OTP : </b>
</label> <input type="text" placeholder="Enter OTP" id="otp" [(ngModel)]=otp
name="otp" required> <br> <br>
<button type="submit" class="loginButton">Login</button>
</div>
<div>
<p style="color: red;">{{ loginStatus }}</p>
</div>
</form>
<router-outlet></router-outlet>
</div>
app.component.ts
import { Component, OnInit } from '#angular/core';
import { Location } from '#angular/common';
import { HomepageComponent } from './homepage/homepage.component';
import { Headers, Http, Response } from '#angular/http';
import { RouterModule, Routes } from '#angular/router';
import { HttpClient } from '#angular/common/http';
import { Directive } from '#angular/core';
//import { Router } from '#angular/router';
import { Router } from "#angular/router";
import { Text } from '#angular/compiler';
export const appRoutes: Routes = [
{path: 'home', component:HomepageComponent}
];
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
otpsubmitted = false;
loginSubmitted = false;
userName = '';
password = '';
otp ='';
userAuthCheck:Text;
checkOtp:Text;
authCheck ='';
loginStatus='';
ngOnInit() {
}
constructor(private http: Http,private httpClient: HttpClient,private route: Router ) { }
private generateOtp(){
this.http.post('http://localhost:8080/loginController/generateotp', {
userMail: this.userName
})
.subscribe(
res => {
console.log(res);
},
err => {
console.log("Error occured");
}
);
}
private logSubmit(){
this.http.post('http://localhost:8080/loginController/authUser', {
userMail: this.userName,
password: this.password,
otp: this.otp
})
.subscribe(
res => {
const printResp=res.json();
console.log(res);
//this.loginStatus=printResp.status;
if (printResp.status === 'true'){
this.loginStatus = '';
console.log('in the clickName');
this.route.navigateByUrl('/home');
//this.route.navigate(['home/']);
} else if(printResp.status === 'false') {
this.loginStatus = printResp.Data.errorMessage;
}
},
err => {
console.log("Error occured"+err);
}
);
}
generateOtpSubmit() {
this.otpsubmitted = true;
this.generateOtp();
}
onLoginSubmit(){
this.loginSubmitted = true;
this.logSubmit();
}
}
app-routing.module.ts
import {ApplicationComponent} from './application/application.component';
import {NavigationComponent} from './navigation/navigation.component';
import { HomepageComponent } from './homepage/homepage.component';
import {AppComponent} from './app.component';
import {NgModule} from '#angular/core';
import {RouterModule, Routes} from '#angular/router';
import { CommonModule } from '#angular/common';
const routes: Routes = [
{path: 'home', component: HomepageComponent},
{path: 'application', component: ApplicationComponent},
{path: 'navigation', component: NavigationComponent},
];
#NgModule({
imports: [CommonModule,RouterModule.forRoot(routes)],
exports: [RouterModule],
declarations: []
})
export class AppRoutingModule {}
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { Router } from '#angular/router';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { AppComponent } from './app.component';
import { HttpModule } from '#angular/http';
import { HttpClientModule } from '#angular/common/http';
import { HomepageComponent } from './homepage/homepage.component';
import { ApplicationComponent } from './application/application.component';
import { NavigationComponent } from './navigation/navigation.component';
import { SearchuserComponent } from './searchuser/searchuser.component';
#NgModule({
declarations: [
AppComponent,
HomepageComponent,
ApplicationComponent,
NavigationComponent,
SearchuserComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
HttpModule,
AppRoutingModule
],
bootstrap: [AppComponent]
})
export class AppModule { }
homepage.component.html
<p>
homepage works!
</p>
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>CyberSecurityVw</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>
</body>
</html>
homepage.component.ts
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-homepage',
templateUrl: './homepage.component.html',
styleUrls: ['./homepage.component.css']
})
export class HomepageComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}

Just use
this.route.navigate(['/home']);

First :you will need to move your login form to a new component called (login)
second :your app component html should hold only this line
<router-outlet></router-outlet>
because app component will act like your landing page so you shouldn't add login form on it
Third : you need to modify your routing
import { HomepageComponent } from './homepage/homepage.component';
import { LoginComponent } from './login/login.component';
import { AppComponent } from './app.component';
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { CommonModule } from '#angular/common';
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{
path: 'home', component: HomepageComponent,
children: [
{ path: '', redirectTo: '/example', pathMatch: 'full' },
{
path: 'example', component: ExampleComponent
}
]
},
{ path: 'login', component: LoginComponent },
];
#NgModule({
imports: [CommonModule, RouterModule.forRoot(routes)],
exports: [RouterModule],
declarations: []
})
export class AppRoutingModule { }
-what will happen is when u type your website url without any routing it will navigate to home/example - so home component should contain your website design template so all children component will inject within home component and take the same template design
-login component is stand alone because u don't need it to take the same website design template
Fourth : in your home page html add this
<div>
//your header
<header></header>
<div class="content">
<router-outlet></router-outlet>
</div>
// your footer
<footer></footer>
</div>
</div>

First add import in your main component
import {Router } from '#angular/router';
In the same file add below code for constructor and method
constructor(private route: Router) {}
public Dashbord()
{
this.route.navigate(['/dashboard']);
}
In app-routing.module.ts file add dashboard
const routes: Routes =
[
{ path: '', pathMatch: 'full' ,component: TestComponent},
{ path: 'dashboard', component: DashboardComponent }
];
This is your .html file code
<button mat-button (click)="Dashbord()">Dashboard</button><br>
Good luck.

Related

Why is the html of my components not displaying after successfully routing to it?

I'm developing an Angular 2 app and I made a router to navigate around the app. While it will successfully go to the correct urls, it won't actually render the html of any component other than AppComponent.
route.module.ts
import { DashboardComponent } from './dashboard/dashboard.component';
import { LoginComponent } from './login/login.component';
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
const routes: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: ":name", component: DashboardComponent}
];
#NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
app.module.ts
import { AppRoutingModule } from './route.module';
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { FormsModule } from '#angular/forms';
import { DashboardComponent } from './dashboard/dashboard.component';
#NgModule({
declarations: [
AppComponent,
LoginComponent,
DashboardComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
login.component.ts
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
name: String;
pass: String;
constructor() {
}
ngOnInit( ) {
}
login(){
if (this.name == "Shai" && this.pass=="jon"){
location.href = "http://localhost:4200/" + this.name;
}
}
}
app.component.ts (the only one that will display)
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
;
}
app.component.html
<app-login></app-login>
Note: This worked perfectly for getting the login component to display but obviously it causes it to display everywhere which isn't a good idea.
I will be very grateful to anybody who can figure out what's wrong with my code.
Edit: Added Templates
login.component.html
<div class="text-center col-sm-2 col-centered" style="padding:50px 0">
<div class="logo"><h1>login</h1></div>
<!-- Main Form -->
<div class="login-form-1">
<form id="login-form" class="text-left">
<div class="login-form-main-message"></div>
<div class="main-login-form">
<div class="login-group">
<div class="form-group">
<label for="lg_username" class="sr-only">Username</label>
<input type="text" [(ngModel)]="name" class="form-control" id="lg_username" name="lg_username" placeholder="username">
</div>
<div class="form-group">
<label for="lg_password" class="sr-only">Password</label>
<input type="password" [(ngModel)]="pass"class="form-control" id="lg_password" name="lg_password" placeholder="password">
</div>
</div>
<button class="login-button" (click)="login()"><i>Login</i></button>
</div>
</form>
</div>
<!-- end:Main Form -->
</div>
dashboard.component.html
<p>Dashboard Works</p>
If you are using angular routing then app.component.html should have <router-outlet></router-outlet> not <app-login></app-login>.
Then router then loads the component you want to view based on the path you enter, I.E. "/login" or "" will load the login component, and inject <app-login></app-login> into the router outlet.
See: https://angular.io/guide/router#router-outlet
The guide here shows you how to structure an app, and implement the routing.

Angular 4 routing is not working

Angular routing is not working.. here is the code
routs.ts: routing url definitions file.
import {BlankComponent} from "../layouts/blank.component";
export const routes=[
{
path:'',
component:BlankComponent,
children:[
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', loadChildren: '../pages/dashboard/dashboard.module#DashboardModule' }
]
},
{ path: '**', redirectTo: 'home' }
]
routes.module.ts: routing module
import {NgModule} from "#angular/core";
import {RouterModule} from "#angular/router";
import { routes } from './routes';
#NgModule({
imports:[RouterModule.forRoot(routes)],
exports:[RouterModule,]
})
export class RoutesModule{
constructor(){
}
}
Layout module:
import {NgModule} from "#angular/core";
import { RouterModule } from '#angular/router';
import {BlankComponent} from "./blank.component";
import {TopnavComponent} from "./topnav.component";
#NgModule({
declarations:[BlankComponent,TopnavComponent],
exports:[BlankComponent,TopnavComponent,RouterModule],
imports:[]
})
export class LayoutsModule{}
BlankComponent:
import {Component} from "#angular/core";
#Component({
selector:"sig-blank",
templateUrl:'./blank.component.html'
})
export class BlankComponent{}
App module:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import {LayoutsModule} from './layouts/layouts.module'
import {RoutesModule} from "./routes/routes.module"
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
LayoutsModule,
RoutesModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
blank.component.html
<div class="wrapper">
<section>
<div class="container">
<router-outlet></router-outlet>
</div>
</section>
</div>
app.component.html
<router-outlet></router-outlet>
This is the code i used in my project. but the routing is not working .
What is the wrong in my code. actually i have markup in my ./blank.component.html which i not included in the question. now the page displaying is the content in app.component.html only
You need to give the component name at {path:'home',component:ComponentName,loadChildren: '../pages/dashboard/dashboard.module#DashboardModule'}

The selector "login-app" did not match any elements while using different component Angular 2

I have a component in angular 2 as shown below
login.component.ts
import { Component } from '#angular/core';
import { LoginViewModel } from "../ViewModel/Login.ViewModel";
import { LoginService } from "../Service/Login.Service";
#Component({
selector: 'login-app',
templateUrl: 'Account/partialLogin',
providers: [LoginViewModel, LoginService]
})
export class LoginComponent {
constructor(private loginservicemodel: LoginService, private model: LoginViewModel) {
this.model.userName = 'erere#ada.com';
this.model.password = "test anand";
}
save(modelValue: LoginViewModel, isValid: boolean) {
if (isValid) {
this.loginservicemodel.loginHttpCall();
}
}
}
Home.Component.ts
import { Component } from '#angular/core';
#Component({
selector: 'Home-app',
template: `
<h1>Angular Router</h1>
<nav>
<a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>
<a routerLink="/heroes" routerLinkActive="active">Heroes</a>
</nav>
<router-outlet></router-outlet>
`
})
export class HomeComponent {
}
The appModule.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { RouterModule, Routes } from '#angular/router';
import { HttpModule, JsonpModule } from '#angular/http';
import { LoginComponent } from "./Components/login.Component";
import { HomeComponent } from "./Components/home.component";
const appRoutes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'Account/Login', component: LoginComponent }
];
#NgModule({
imports: [BrowserModule, FormsModule, HttpModule, JsonpModule, RouterModule.forRoot(appRoutes)],
declarations: [LoginComponent, HomeComponent],
bootstrap: [HomeComponent]
})
export class AppModule { }
login.cshtml
#{
ViewData["Title"] = "Login";
}
<login-app>looding...</login-app>
partialLogin.cshtml
<router-outlet></router-outlet>
<p>THis is test</p>
Routing
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "spa-fallback",
template: "{*url}",defaults: new { controller = "Home", action = "Index" });
});
I have use the angular 2 routing as you can see in the appmodule.ts.If I navigate to homepage i,e Home/Index I will get an error as The selector "login-app" did not match any elements and when I navigate to Account/Login I will get an error as The selector "Home-app" did not match any elements.I know the the condition on appmodule is not working. How can I make this work. Please anyone can solve this issue
you are getting this error because you didn't import all your other component in you ngModule file. add them in declaration just like you have imported LoginComponent
#NgModule({
imports: [BrowserModule, FormsModule, HttpModule, JsonpModule],
declarations: [LoginComponent],<-- add all your component here
bootstrap: [LoginComponent]
})
export class AppModule { }
Below is an example of how to add route in Angular2:
//Create new app.module.ts file
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { LoginComponent } from './Components/login.Component';
const appRoutes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'login', component: LoginComponent}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
//Import the above define route in your App module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { HttpModule, JsonpModule } from '#angular/http';
import { LoginComponent } from "./Components/login.Component";
//Import your route file
import { routing } from './app.routing';
#NgModule({
imports: [BrowserModule, FormsModule, HttpModule, JsonpModule,routing,],
declarations: [LoginComponent],
bootstrap: [LoginComponent]
})
export class AppModule { }
Finally the working code.Call the respective selector in HTML page
AppModule.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { RouterModule, Routes } from '#angular/router';
import { HttpModule, JsonpModule } from '#angular/http';
import { ModuleWithProviders } from '#angular/core';
import { AppComponent} from "./app.component";
import { LoginComponent } from "./Components/login.Component";
import { HomeComponent } from "./Components/home.component";
const appRoutes: Routes = [
{ path: '', redirectTo: 'Home/Index', pathMatch: 'full' },
{ path: 'Account/Login', component: LoginComponent },
{ path: 'Home/Index', component: HomeComponent }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
#NgModule({
imports: [BrowserModule, FormsModule, HttpModule, routing],
declarations: [AppComponent,LoginComponent, HomeComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
app.Component.ts
import { Component } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
#Component({
selector: 'main-app',
template: '<router-outlet></router-outlet>'
})
export class AppComponent { }
Home.Component.ts
import { Component } from '#angular/core';
#Component({
selector: 'Home-app',
template: `
<h1>Angular Router</h1>
<nav>
<a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>
<a routerLink="/heroes" routerLinkActive="active">Heroes</a>
</nav>
`
})
export class HomeComponent {
}
login.Component.ts
import { Component } from '#angular/core';
import { LoginViewModel } from "../ViewModel/Login.ViewModel";
import { LoginService } from "../Service/Login.Service";
#Component({
selector: 'login-app',
templateUrl: 'Account/partialLogin',
providers: [LoginViewModel, LoginService]
})
export class LoginComponent {
constructor(private loginservicemodel: LoginService, private model: LoginViewModel) {
this.model.userName = 'erere#ada.com';
this.model.password = "test anand";
}
save(modelValue: LoginViewModel, isValid: boolean) {
if (isValid) {
this.loginservicemodel.loginHttpCall();
}
}
}

Cannot match any routes: '' angular 2 asp.net core

I have a one main page and I want to separate header body and footer. Because in other page I wont be needed header.
_layout.cshtml
<!DOCTYPE html>
<html>
<head>
<base href="/" />
</head>
<body>
<main-app></main-app>
</body>
</html>
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { RouterModule, Routes } from '#angular/router';
import { HttpModule, JsonpModule } from '#angular/http';
import { ModuleWithProviders } from '#angular/core';
import { AppComponent} from "./app.component";
import { EqualValidator } from "./Validation/equal.validator.directive";
import { LoginComponent } from "./Components/login.Component";
import { HomeComponent } from "./Components/home.component";
import { DashBoardComponent } from "./Components/dashBoard.Component";
import { FooterComponent } from "./Components/footer.Component";
const appRoutes: Routes = [
{ path: '', redirectTo: 'Home/Index', pathMatch: 'full' },
{ path: 'Account/Login', component: LoginComponent },
{ path: 'Home/Index', component: HomeComponent,children:[
{path: '',component: FooterComponent,outlet: 'footer'}]},
{ path: 'DashBoard/Index', component: DashBoardComponent}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
#NgModule({
imports: [BrowserModule, FormsModule, HttpModule, routing],
declarations: [AppComponent, LoginComponent, HomeComponent, DashBoardComponent, EqualValidator,FooterComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
If I remove the child routing the application works good. I have added the forChild() root also but the footer component is not been loaded.
Here I found the working sample
https://plnkr.co/edit/sgGDpti43GPM5cHntPpu?p=preview
But I am facing the Cannot match any routes: '' error
home.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'Home-app',
template: `
<br>
<br>
<br>
my home!!!!
<br>
<br>
<br>
<router-outlet name="footer"></router-outlet>
`
})
export class HomeComponent {
}
footer.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'Footer-app',
templateUrl: '<p>Copy rights emakitri 2017</p>'
})
export class FooterComponent {
constructor() {
console.log("test");
}
}

Angular 2 - routing inside a component

Yesterday I asked a question about an another specific thing of angular 2 routing and the answer was satisfying for me Angular 2 — navigate through web pages without reloading a component that is common for those pages . But when I got back to examining these things, I encountered a problem again. Here's the new version of the app: http://ivan-khludov.com/ . What if I want the pages of the private section to have a shared component (a counter in my example), don't reload it each time I navigate withing the section and at the same time display different components at different pages - the dashboard component at private/dashboard and the inbox component at private/inbox? Is it possible to do without reloading the counter and without storing the last value of the counter in memory? This is the entry point of the application and the root module:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { HttpModule } from '#angular/http';
import { RouterModule } from '#angular/router';
import { BrowserModule } from '#angular/platform-browser';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { ROUTES } from './routes';
import { AppWrapper } from './components/app-wrapper';
import { PublicSection } from './components/public';
import { PrivateSection } from './components/private';
import { Counter } from './components/counter';
import { Dashboard } from './components/private/dashboard';
import { Inbox } from './components/private/inbox';
#NgModule({
imports: [
BrowserModule,
CommonModule,
HttpModule,
RouterModule.forRoot(ROUTES)
],
declarations: [
AppWrapper,
PublicSection,
PrivateSection,
Counter,
Dashboard,
Inbox
],
providers: [
],
bootstrap: [
AppWrapper
]
})
class RootModule {}
platformBrowserDynamic().bootstrapModule(RootModule);
Routing:
import { Routes } from '#angular/router';
import { AppWrapper } from '../components/app-wrapper';
import { PublicSection } from '../components/public';
import { PrivateSection } from '../components/private';
export const ROUTES: Routes = [
{
path: '',
redirectTo: '/public/1',
pathMatch: 'full'
},
{
path: 'section-1',
redirectTo: '/public/1',
pathMatch: 'full'
},
{
path: 'public/:page',
component: PublicSection
},
{
path: 'private',
redirectTo: '/private/dashboard',
pathMatch: 'full'
},
{
path: 'private/:page',
component: PrivateSection
}
];
The private section component:
import { Component } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
#Component({
selector: 'private',
template: `
<h2>Private section — {{page}}</h2>
<counter></counter>
<dashboard></dashboard>
<inbox></inbox>
`
})
export class PrivateSection {
private page: string;
private sub: any;
constructor(
private route: ActivatedRoute
) {
}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.page = params['page'];
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
The dashboard component:
import { Component } from '#angular/core';
#Component({
selector: 'dashboard',
template: `
<div>dashboard text: lorem ipsum</div>
`
})
export class Dashboard {
}
The inbox component:
import { Component } from '#angular/core';
#Component({
selector: 'inbox',
template: `
<div>inbox text: dolor sit amet</div>
`
})
export class Inbox {
}
Thanks in advance for your answers.

Categories