How to render a component without rendering AppComponent at all times? - javascript

I want to render 2 components (AppComponent and UserComponent) without having to render AppComponent at all times. Here's what my code looks like:
app.routing.module.ts
const routes: Routes = [
{
path: '', component: AppComponent
},
{
path: 'user', component: UserComponent
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.component.html
<div>
I'm in the app component
</div>
<router-outlet></router-outlet>
Now for some reason "I'm in the app component" text is rendered 2 times as you can see in the picture:
Now when I go to route '/user' I see this:
so my question is How can I only see "I'm in the app component" text when on on '/' route and
when I'm on '/user' route only see "user works!"? Thanks a lot in advance!

AppComponent renders by default as its the root component. You would need to create another component and use that as your home component. Please check the updated stackblitz.

My answer is: Don't. Make an OtherComponent, then remove all but the <router-outlet> tag from AppComponent.html.
Treat that AppComponent as the top level that everything flows through. Angular is very opinionated, and if you do things in a way that's not standard practice, Angular will act like it's meant to.
If the two branches should really be that separate, consider having separate apps.

This is because default route '' matches both '' and 'user' paths. Try setting pathMatch: 'full' to the AppComponent and it shouldn't render on other routes:
{
path: '',
component: AppComponent
pathMatch: 'full'
}
But more of an issue here is that the default route should be a separate component and your AppComponent should be the one that holds the router-outlet.

Related

How many router outlets can i use in angular

Hello i just want to know how many router-outlets i can use in angular, is there any limit?
if so how many?
Here is the link to understand "multiple outlet", for anyone who is not aware of this!
https://medium.com/angular-in-depth/angular-router-series-secondary-outlets-primer-139206595e2
Thank You
there is no limit on the outlets, however every outlet corresponds to a piece of code, that will be rendered there, and it affects the url. With more code your app will be loaded longer and there are some restrictions on url length. apart from these 2 I don't think there is any limit
If you want to use multiple <router-outlet></router-outlet> you can use it. There is no limit in angular but there are some best practices of using multiple
place one in app.component.html and if you have a number of featured modules then you can use separate for each featured module.
====== app.component.html=====
<app-header></app-header>
<!-- router-outlet will emit an activate event any time a new component is being instantiated, and a deactivate event when it is being destroyed. -->
<!-- It will act as a placeholder that angular automatically fills the current route state-->
<router-outlet></router-outlet>
<app-footer></app-footer>
======= app-routing.ts =====
export const routes: Routes = [
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' , canActivate : [AuthGuardService]},
{ path: 'dashboard', component: DashboardComponent, canActivate : [AuthGuardService], data: {role: 'system'}},
{ path: 'featureModule', loadChildren: './module/featureModule.module#FeatureModule', canActivate : [AuthGuardService]},
{ path: '**', component: NotFoundComponent }
];
and in FeatureModule add saparate <router-outlet> so all components in featuredModule will get rendered in FeatureModuleComponent.html.
featureModuleComponent.Html
<app-menu [sysType]="featureModule"></app-menu>
<div class="bg-mage" [ngStyle]="{'background-image': backgroundImage, 'height': customImgHeight} ">
<router-outlet></router-outlet> <!-- router outlet of featured module -->
</div>
is there any limit?
No, there is no specific limit.

Multiple named router-outlet - component imported but not initialized and rendered

I'm using multiple named angular 8 router-outlet in a web app. All the routerLink seems to work as it changes the URL but components in my 2nd router-outlet are imported but not initialized nor rendered.
I made a Stackblitz available here : https://stackblitz.com/edit/ng-multiple-router-outlet?file=src/app/app.component.ts
As you can see, when you click on the sidebar, under photos you have a second navigation level by clicking on Google or Facebook but nothing is rendered.
In modules, components used in other modules and RouterModule are well exported to be accessible, I don't see what I've done wrong.
I tried to declare the routes with both forRoot and forChild methods, I put some logs, but I'm running out of clues.
Thanks for your help !
Angular router is pretty simple once you understand how nested routes works there.
Let's imagine a simple configuration:
RouterModule.forRoot([
{
path: '',
component: HomeComponent,
children: [
{ path: 'child', component: ChildComponent }
]
}
])
How would you use router-outlet to cover all routes above?
app.component.html
\
contains
\
<router-outlet></router-outlet>
\/
renders
\
HomeComponent
home.component.html
\
contains
\
<router-outlet></router-outlet>
renders
\
ChildComponent
The main takeaway here is that router-outlet renders component depending on router context. Once it renders component a new context is created and all router-outlet's declared at this level will look at children configuration.
The same is true for named routes.
You've generated the link like:
(selection:facebook//sidebar:photos)
It means that these named routes should be at the same root level. But you defined <router-outlet name="selection"></router-outlet> at nested level inside rendered by router LibraryComponent.
Let's add this outlet at the same level as 'sidebar':
<router-outlet name="sidebar"></router-outlet>
<router-outlet name="selection"></router-outlet>
and it actually works stackblitz
Now let's come back to your attempt. If you want to render selection components inside selection.component.html then you should be using nested named routed links:
selection.component.html
[routerLink]="['.', { outlets: { selection: [routeName] } }]"
\/
relative path
The above binding will generate nested links like (sidebar:photos/(selection:facebook))
Now you need to move SelectionRoutes configuration to children property of photos path:
selection.module.ts
imports: [
CommonModule,
RouterModule, //.forChild(SelectionRoutes)
],
sidebar.routes.ts
import { SelectionRoutes } from '../selection/selection.routes';
...
export const SidebarRoutes: Route[] = [
{ path: 'photos', component: LibraryComponent, outlet: 'sidebar', children: SelectionRoutes },
Stackblitz Example
Update
In order to make facebook as a default subroute you create a route with redirectTo option like:
export const SelectionRoutes: Route[] = [
{ path: 'facebook', component: FacebookComponent, outlet: 'selection' },
{ path: 'google', component: GoogleComponent, outlet: 'selection' },
{ path: '', redirectTo: '/(sidebar:photos/(selection:facebook))', pathMatch: 'full', },
]
Stackblitz Example

Router not correctly loading default route on application load

I've been struggling with this issue for the past day and a half and still have made no progress. Currently, I am attempting to load my angular app and have it default to a particular page when the application is bootstrapped. Unfortunately, it redirects to a different route.
I'm trying to go to:
https://clwd0002278/ControlTower/NICK/UI/#/
When I initially load, though, it goes to https://clwd0002278/ControlTower/NICK/UI/#/ControlTower/NICK/UI/, which results in the 404 page being hit.
I'll also try to go to https://clwd0002278/ControlTower/NICK/UI/ with the same result as above.
Here's the code so someone can try to make sense of this:
const routes: Routes = [
{path: '', redirectTo: 'patients', pathMatch: 'full'},
{path: 'dashboard', component: DashboardComponent},
{path: 'notifications', component: NotificationsComponent},
{path: 'patients', component: PatientListComponent},
{path: '404', component: NotFoundComponent},
{path: '**', component: NotFoundComponent},
];
#NgModule({
imports: [
RouterModule.forRoot(routes, {useHash: true})
],
exports: [RouterModule]
})
export class AppRoutingModule {
}
Here's the base-href on the html page:
<base href="#">
I have tried changing base-href and deploy-url in the build script, as well as omitting them entirely. I'm just not sure what I'm missing at this point.
Any help would be appreciated, and just ask if you need more information.
Edit:
The application exists at https://clwd0002278/ControlTower/NICK/UI/ and NOT at https://clwd0002278/.
Add
<head>
<base href="/ControlTower/NICK/UI">
...
</head>
to your index.html
or provide int in AppModule like
import { APP_BASE_HREF } from '#angular/common';
...
providers: [{APP_BASE_HREF, useValue: '/ControlTower/NICK/UI'}]
See also
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base
https://angular.io/api/common/APP_BASE_HREF
Always your default route must be at the before the path "**".
{path: '404', component: NotFoundComponent},
{path: '', redirectTo: 'patients', pathMatch: 'full'},
{path: '**', component: NotFoundComponent},
Refer
https://angular.io/guide/router
So, it turns out that there was some code from ngrx that was pulled in from our base project package that kept throwing the location.pathname onto the end of the url for the angular/ngrx routing packages. I'm so frustrated and yet so relieved to have finally resolved this issue.
I commented out the reducers and initial state related to this to solve my issue. So, be careful of how ngrx interacts with your url!

Angular navigating from AppComponent to another Component

I have the following setup:
in app-routing module:
export const routes: Routes = [
{ path: '', component: AppComponent },
{ path: 'Role', component: RoleComponent }
];
In app.module.ts, I have:
imports: [
RouterModule.forRoot(routes)
],
In app.component.html, I have
Test
view above is an iframe. However, it doesn't find the role component to go to role.component.html page and open it in iframe.
BTW, role component files are in a folder called role under app directory where the app.component.html is.
app > app.component.html, ts, css
app > role > role.component.html, ts, css
And obviously everything compiles fine in VS Code.
Any ideas whats missing?

Routing in angular disables javascript functions

I have a simple angular routing module that looks like this:
import { NgModule, ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomeComponent } from './../../home/home.component';
import { LoginComponent } from './../../login/login.component';
const routes: Routes = [
{
path: '',
component: HomeComponent
},
{
path: 'login',
component: LoginComponent
}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
The HomeComponent is loaded at first whenever I open the page. everything works fine until I switch to the login page. Both of them have certain parts that work with javascript. I added those in the .angular-cli.json file.
If I switch to the login page using the following button:
<li class="active"><a routerLink="">Home</a></li>
none of those functions seem to work, also whenever I switch back to the homepage component, the functions that did work before won't work here either.
So far i found out that the scripts are loaded once since the main application is loaded using "eager loading" and the compontens use "lazy loading".
Is there a way to load the scripts again or any other way to fix this?
I managed to fix the problem by using the solution given on the following page:
how to load js on component level in angular 4. I don't want to load all js file at app startup
given by Milad.

Categories

Resources