I am trying to learn Angular 2 and play with it now. But I don't know why it doesn't go to start page from AppComponent. As long as I know, this has to move to test page and show "test" text. But when I run this, it only displays "Hello" which is app.component text. If I enter /test url, there is 404 error. Is this because the test component is not loaded successfully?
main.ts
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { AppComponent } from './app.component';
import { routing } from './app.routing';
import { test } from './test';
#NgModule({
imports: [
BrowserModule,
routing
],
declarations: [
AppComponent,
test
],
providers: [
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
app.routing.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { test } from './test.index';
const routes: Routes = [
{ path: '', component: test },
{ path: 'test', component: test },
{ path: '**', redirectTo: '' },
];
export const routing = RouterModule.forRoot(routes);
app.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template: `<h1>Hello </h1>`,
})
export class AppComponent { }
test.ts
import { Component } from '#angular/core';
#Component({
selector: 'test-app',
template: `<h1>test </h1>`,
})
export class test {}
Include '<router-outlet></router-outlet>' in your appcomponent template:
<div>
<h3>App component</h3>
</div>
<div>
<router-outlet></router-outlet>
</div>
It looks like you need to provide a <router-outlet></router-outlet> in your app.component.ts template.
So the test component isn't being loaded because it can't inject the component into anything without the <router-outlet>.
https://angular.io/tutorial/toh-pt5#add-routeroutlet
Related
I have trouble to direct an angular page to another component which i created. It should be directed to 'belize-local-time-component' when I click "take me back". But for right now, when I click "take me back", it directed to 'belize-local-time-component'page, but it did not stay, instead of coming back to the current page. Please help!! Thank you.
welcome-component.component.html
<p>
This is what I'm all about. <strong>Take me back</strong>.
</p>
welcome-component.component.ts
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { Router } from '#angular/router';
#Component({
selector: 'app-welcome-component',
templateUrl: './welcome-component.component.html',
styleUrls: ['./welcome-component.component.css']
})
export class WelcomeComponentComponent implements OnInit {
constructor(private route: ActivatedRoute,private router: Router) {
this.route.params.subscribe(res => console.log(res.id));
}
ngOnInit() {
}
sendMeHome() {
this.router.navigate(['./belize-local-time-component']);
}
}
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { WelcomeComponentComponent } from './welcome-component/welcome-component.component';
import { BelizeLocalTimeComponentComponent } from './belize-local-time-component/belize-local-time-component.component';
import { AppRoutingModule } from './/app-routing.module';
import { FormsModule } from '#angular/forms';
import { Routes, RouterModule } from '#angular/router';
#NgModule({
declarations: [
AppComponent,
WelcomeComponentComponent,
BelizeLocalTimeComponentComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { WelcomeComponentComponent} from './welcome-component/welcome-component.component';
import { BelizeLocalTimeComponentComponent } from './belize-local-time-component/belize-local-time-component.component';
import { Route } from '#angular/compiler/src/core';
import { Routes, RouterModule } from '#angular/router';
const routes: Routes = [
{
path: '',
component: WelcomeComponentComponent
},
{
path: 'belize-local-time-component',
component: BelizeLocalTimeComponentComponent
}
];
#NgModule({
imports:[RouterModule.forRoot(routes)],
exports:[RouterModule]
})
export class AppRoutingModule { }
The problem is with your anchor tag in Welcome component. You should remove href="" or use a button instead. Please check this sample that I have created for you:
https://stackblitz.com/edit/angular-yarabq
Swap the order of the paths in your routes.
Im learning to use Angular 4 and im not being able to render more than 1 template, my starting App template is OK, and it renders fine, but then i created 2 more components with "ng g component newComponent" and im not being able to make them display anything. I can type the new components URL in the browser and it navigates fine without errors, but it always displays the app.component.html My files are like this:
app.component.html
<!--The content below is only a placeholder and can be replaced.-->
<p>
ASDASDASDAS
</p>
app.component.ts
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent {
}
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { DashboardComponent } from './dashboard/dashboard.component';
const appRoutes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'dashboard', component: DashboardComponent }
];
#NgModule({
declarations: [
AppComponent,
LoginComponent,
DashboardComponent
],
imports: [
BrowserModule,
RouterModule.forRoot(
appRoutes,
{ enableTracing: true }
)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
dashboard.component.html
<p>
dashboard works!
</p>
dashboard.componentspec.ts
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { DashboardComponent } from './dashboard.component';
describe('DashboardComponent', () => {
let component: DashboardComponent;
let fixture: ComponentFixture<DashboardComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ DashboardComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(DashboardComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
});
dashboard.component.ts
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.less']
})
export class DashboardComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
My login component is similar, and my three components displays the same:
ASDASDASDAS
I dont know where my problem is, i have no error messages in any of the consoles. My project Structure is:
-src
--app
---dashboard
----dashboard.component.html
----dashboard.component.less
----dashboard.component.spec.ts
----dashboard.component.ts
---login
----login.component.html
----login.component.less
----login.component.spec.ts
----login.component.ts
--app.component.html
--app.component.less
--app.component.spec.ts
--app.component.ts
--app.module.ts
Do i need different NgModules for my purpose of totally separated views? I mean i want a page with "Login", another for "Dashboard", another for idk, a new page...etc, each one needs an NgModule for having separated views?
Any help is much appreciated!!
You should place <router-outlet></router-outlet> into app.component.html to define a place where other components will be rendered.
An example of app.component.html content:
<div class="app">
<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>
</div>
You can read more here.
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'}
Repo: https://github.com/leongaban/lifeleveler.io
Not sure why I'm getting this error, I have Router imported in my app.component.ts
I'm trying to use the app.component to hold the main <router-outlet>, and serve up the login view first.
app.module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { RouterModule } from '#angular/router';
import { routing } from './app.routing';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { AuthService } from './shared/services/auth.service';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/observable/throw';
#NgModule({
imports: [
BrowserModule,
FormsModule,
RouterModule,
routing
],
declarations: [
AppComponent,
LoginComponent
],
providers: [
AuthService,
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
app.component.ts
import { Component, OnInit } from '#angular/core';
import { User } from './shared/models/user';
import { Router } from '#angular/router';
#Component({
selector: 'my-app',
templateUrl: './app/app.component.html',
styleUrls: ['./app/app.component.css']
})
export class AppComponent implements OnInit {
ngOnInit() {
}
}
app.component.html
<router-outlet></router-outlet>
app.routing.ts
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { LoginComponent } from './login/login.component';
export const routes: Routes = [
{
path: '',
redirectTo: '/login',
pathMatch: 'full',
},
{
path: 'login',
component: LoginComponent
}
]
export const routing: ModuleWithProviders = RouterModule.forRoot(routes);
I just refactored your project with webpack , your same code works just fine:
github repo
first :
npm install -g #angular/cli
npm install
ng serve
It looks like you might be importing the RouterModule multiple times.
I would remove this line from your app.routing.ts
export const routing: ModuleWithProviders = RouterModule.forRoot(routes);
In your app.module I would import your routes with:
import { routes } from './app.routing';
And then import the RouterModule as:
RouterModule.forRoot(routes)
You should add the RouterModule.forRoot(routes) statement inside your AppModule:
#NgModule({
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot(routes)
],
declarations: [
AppComponent,
LoginComponent
],
providers: [
AuthService,
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
and remove it from your app.routing.ts file:
export const routes: Routes = [
{
path: '',
redirectTo: '/login',
pathMatch: 'full',
},
{
path: 'login',
component: LoginComponent
}
];
Just import RouterOutlet
import { RouterOutlet } from '#angular/router';
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();
}
}
}