Angular 4 doesnt display my components views - javascript

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.

Related

'<selector>' is not a known element

Before I continue with the question: I have checked the other questions with the same title and I have followed given advices. None of it helped so I decided to open a new question.
I have angular project with one module and multiple components. Dashboard component uses welcome component that is apparently not recognized.
The module has the following code:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { HomeComponent } from './home/home.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { FrameComponent } from './frame/frame.component';
import { WelcomeComponent } from './welcome/welcome.component';
import { CardComponent } from './card/card.component';
import { AlertComponent } from './alert/alert.component';
#NgModule({
declarations: [
FrameComponent,
HomeComponent,
CardComponent,
WelcomeComponent,
AlertComponent
],
imports: [
BrowserModule,
RouterModule.forRoot([
{
path: '',
component: HomeComponent
},
{
path: 'dashboard',
component: DashboardComponent
}
])
],
exports: [CardComponent, WelcomeComponent, AlertComponent],
providers: [],
bootstrap: [FrameComponent]
})
export class AppModule { }
As you can see, I have imported WelcomeComponent, declared it and exported it.
WelcomeComponent contains the following code:
import { Component, OnInit, Input } from '#angular/core';
#Component({
selector: 'app-welcome',
templateUrl: './welcome.component.html',
styleUrls: ['./welcome.component.css']
})
export class WelcomeComponent implements OnInit {
#Input()
message: string;
welcomeMessage: string;
constructor() { }
ngOnInit(): void {
}
}
Here you can see app-welcome as a selector. It appears to be connected correctly. But when I use it in dashboard.component.html as given from the example
<app-welcome [message]="message" [welcomeMessage]="welcomeMessage"></app-welcome>
I get the following error:
Error: src/app/dashboard/dashboard.component.html:18:5 - error NG8001: 'app-welcome' is not a known element:
1. If 'app-welcome' is an Angular component, then verify that it is part of this module.
2. If 'app-welcome' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '#NgModule.schemas' of this component to suppress this message.
Other errors are related to welcome and welcomeMessage not existing since component is not recognized.
I tried restarting server, running it as --prod. I tried everything that I found. Does anyone know what could this cause?
Dashboard component is not declared in your AppModule, that's the problem.
Also you don't need to export the components in that case, just declare them.

Angular 2 does not move to start page from AppComponent

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

error "ERROR TypeError: Cannot read property 'createComponent' of undefined" when work with dynamic component in Angular2

I am trying to add the components dynamically in angular4.
I checked with other questions, But i cant find solution.
I got the error
ERROR TypeError: Cannot read property 'createComponent' of undefined
on dynamic components.
adv.component.ts
import { Component, OnInit, AfterContentInit, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '#angular/core';
import { SampleComponent } from '../sample/sample.component';
#Component({
selector: 'app-adv',
templateUrl: './adv.component.html',
styleUrls: ['./adv.component.css']
})
export class AdvComponent implements OnInit, AfterContentInit {
#ViewChild('container', {read:'ViewContainerRef'}) container;
constructor(private resolver : ComponentFactoryResolver) { }
ngOnInit() {
}
ngAfterContentInit(){
const sampleFactory = this.resolver.resolveComponentFactory(SampleComponent);
this.container.createComponent(sampleFactory);
}
}
adv.component.html
<div #container></div>
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { AdvComponent } from './adv/adv.component';
import { SampleComponent } from './sample/sample.component';
#NgModule({
declarations: [
AppComponent,
AdvComponent,
SampleComponent
],
entryComponents:[
SampleComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
About ngAfterViewInit in docs:
Respond after Angular initializes the component's views and child
views.
while ngAfterContentInit:
Respond after Angular projects external content into the component's
view.
So the child view is not ready in ngAfterContentInit, so move this part
ngAfterContentInit(){
const sampleFactory = this.resolver.resolveComponentFactory(SampleComponent);
this.container.createComponent(sampleFactory);
}
to
ngAfterViewInit() {
const sampleFactory = this.resolver.resolveComponentFactory(SampleComponent);
this.container.createComponent(sampleFactory);
}
Also change:
#ViewChild('container', {read:'ViewContainerRef'}) container;
to
#ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef

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'}

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