Do we need a selector for a router-outlet component? - angular-routing

Say I have this:
<router-outlet></router-outlet>
And in the router:
const routes: Routes = [
{ path: 'about', component: AboutComponent},
{ path: '404', component: PageNotFoundComponent },
{ path: '', component: EmptyComponent, pathMatch: 'full' },
{ path: '**', redirectTo: '/404' }
];
And the component:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-home', // do we want/need this? Or should I remove?
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
if I go to /about, it should render the about page to the <router-outlet> element, so I don't think I need a selector field do I?

If you like you could delete the selector.
But that means that you cannot use <app-home></app-home> in any other template.

You may not need selector for routing purpose strictly but may be needed for directives etc. I would keep select though routing-outlet may not use.

Related

Issue with angular routing. pathMatch : 'full' not working when adding routers dynamically from DB

I have a setup as below.
I am adding router from my database into angular router module,
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { ApplicationDashboardComponent } from './components/application-dashboard/application-dashboard.component'
import { AppService } from './app.service'
import { HttpErrorResponse, HttpResponse } from '#angular/common/http';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private router: Router, protected appService: AppService) {
this.appService.getAllRoutes().subscribe(
(res: HttpResponse<string>) => {
let routerArray = <any>res.body;
if (routerArray !== undefined && routerArray !== 'null' && routerArray !== null) {
if (routerArray.length > 0) {
for (let i = 0; i < routerArray.length; i++) {
routerArray[i].component = ApplicationDashboardComponent;
this.router.config.push({ path: routerArray[i]['path'], component: ApplicationDashboardComponent, data: routerArray[i]['data'], pathMatch: 'full' });
}
}
console.log(this.router);
}
},
(res: HttpErrorResponse) => this.onError(res.message)
)
}
ngOnInit() {
}
protected onError(errorMessage: string) {
console.log(errorMessage);
}
}
And the app.routing.module.ts looks like below,
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { AdminLogoutComponent } from './components/admin/admin-logout.component';
import { AdminComponent } from './components/admin/admin.component';
import { ApplicationDashboardComponent } from './components/application-dashboard/application-dashboard.component'
const routes: Routes = [
{path: '', component: ApplicationDashboardComponent, data:{portfolio:"Risk & Independence", fileName:"R&I-application-list.json"}, pathMatch : 'full'},
{path: 'admin', component: AdminComponent, pathMatch : 'full'},
{path: 'logout', component: AdminLogoutComponent}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
For the ones already added in the route it works. But the ones I am adding from api add does not work without hash. If I try to go to the link without has it is giving me an error "Cannot match any routes. URL Segment"
I have tried to set usehash as false as well as pathlocationstrategy but nothing works.

How to do a lazy loaded ionic framework app with a login page

I have an app that is working great, but I want to move it behind a login page. The various modules are lazy-loaded and have been working great. However, when I change the app to always go to the login page first (where I will check login status and redirect to the app if logged in), I get an error about routes.
app-routing.module.ts
import { NgModule } from '#angular/core';
import { PreloadAllModules, RouterModule, Routes } from '#angular/router';
const routes: Routes = [
{ path: '', loadChildren: './login/login.module#LoginPageModule' }
// this next line was how the app routed before I tried adding the login page
// { path: '', loadChildren: './tabs/tabs.module#TabsPageModule' }
];
#NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule {}
login.router.module.ts
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { LoginPage } from './login.page';
const routes: Routes = [
{ path: '', component: LoginPage },
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class LoginRoutingModule { }
login.page.ts
import { ChangeDetectionStrategy, Component } from '#angular/core';
import { Router } from '#angular/router';
import { Store } from '#ngrx/store';
import { AppState } from '../_store/store/app.store';
import { filter } from 'rxjs/operators';
#Component({
selector: 'app-login',
templateUrl: 'login.page.html',
styleUrls: ['login.page.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class LoginPage {
constructor(private router: Router, private store: Store<AppState>) {
this.userSubscription = this.store.select(state => state.users.user).pipe(
filter(user => !!user)
).subscribe(user => {
if (user) {
// THIS IS WHERE THE ERROR HAPPENS
this.router.navigate(['/tabs']);
}
});
}
}
this.router.navigate(['/tabs']); is where the error happens:
ERROR Error: Uncaught (in promise): Error: Cannot match any routes.
URL Segment: 'tabs/behaviors' Error: Cannot match any routes. URL
Segment: 'tabs/behaviors'
I'm sure I'm missing something really obvious here. First attempt at lazy loading all the modules. I'm pretty certain I need to reference the tabs module in the login.page file somehow, or in the login.router.module. Any help would be greatly appreciated. The state check for user status works great, I've verified that all of that is working, it is just where it attempts to navigate if user is found.
Try to change to
const routes: Routes = [
{ path: '', redirectTo: 'login', pathMatch: 'full' },
{ path: 'login', loadChildren: './login/login.module#LoginPageModule' }
{ path: 'tabs', loadChildren: './tabs/tabs.module#TabsPageModule' }
];
With this code this.router.navigate(['/tabs']); you are routing to tabs, but you don't have it declare it. This is for the app.routing.ts file. Don't understand why you have the login.router.ts file.
So after following a suggestion above, and that giving me the same error, and finding no help in the docs for either angular or ionic, I went on a multi-hour change every combination of routings I could and finally something worked.
These are the routes in the app-routing.module.ts
{ path: 'login', loadChildren: './login/login.module#LoginPageModule' },
{ path: 'tabs', loadChildren: './tabs/tabs.module#TabsPageModule' },
{ path: '', redirectTo: 'login', pathMatch: 'full' },
This is the tabs.router.module.ts before the change that made it work:
{ path: 'tabs', component: TabsPage, children: [ .... ] },
{ path: '', redirectTo: 'tabs/behaviors', pathMatch: 'full' }
This is it now:
{ path: '', component: TabsPage, children: [ ... ] },
That's it. Finally figured it out when accidentally typing in the browser .com:8100/tabs/tabs/behaviors worked. Removing the path: 'tabs' in the tabs routing module fixed it. /tabs goes to the tabs routing, and then /behaviors is the child. My code had added a 2nd layer of /tabs in between the 1st and the /behavior.

PageNotFound route in root routes triggered after outsourcing routes to component

my routes used to work fine when they were all together, the notfound route
{ path: '**', component: PageNotFoundComponent}
was at the last place to capture any other not defined paths.
After I moved the recipe routes to its own module these are never called. Instead, the pagenotfound is called.
Everything works fine if I remove the PageNotFoundComponent route from the root routes. Any ideas regarding whats going on here?
This is the root app routing module:
import { Routes, RouterModule } from '#angular/router';
import { NgModule, OnInit } from '#angular/core';
import { ShoppingListComponent } from './shopping-list/shopping-list.component';
import { PageNotFoundComponent } from './errors/page-not-found/page-not-found.component';
import { AuthComponent } from './auth/auth.component';
const appRoutes: Routes = [
{ path: '', redirectTo: 'recipes', pathMatch: 'full' },
{ path: 'shopping-list', component: ShoppingListComponent },
{ path: 'auth', component: AuthComponent },
{ path: '**', component: PageNotFoundComponent}
];
#NgModule({
imports: [RouterModule.forRoot(appRoutes)],
exports: [RouterModule]
})
export class AppRoutingModule {
OnInit() {
console.log(appRoutes);
}
}
This is the child recipe routing module:
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { RecipesComponent } from './recipes.component';
import { AuthGuard } from '../auth/auth.guard';
import { RecipeStartComponent } from './recipe-start/recipe-start.component';
import { RecipeEditComponent } from './recipe-edit/recipe-edit.component';
import { RecipeDetailComponent } from './recipe-detail/recipe-detail.component';
import { RecipesResolverService } from './recipes-resolver.service';
const routes: Routes = [
{
path: 'recipes', component: RecipesComponent, canActivate: [AuthGuard] , children: [
{ path: '', component: RecipeStartComponent },
{ path: 'new', component: RecipeEditComponent },
{
path: ':id',
component: RecipeDetailComponent,
resolve: [RecipesResolverService]
},
{
path: ':id/edit',
component: RecipeEditComponent,
resolve: [RecipesResolverService]
},
]
}
];
#NgModule({
declarations: [
],
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class RecipesRoutingModule {
}
Thanks for taking the time to get this far, any idea would be appreciated.
The problem was that the wildcard route ('**') always should be at the end of your routes list because of the way it works.
It watches all the routes before it, and checks if any given URL, that the user is searching on matches those.
Since you've outsourced your recipes paths, and probably imported them into app.module, those paths get concatenated after the original path list that you have in your app-routing.module.
Therefore your paths in the recipe routing module end up being AFTER the wildcard route ('**'), so they get ignored by it. That's why searching on any URL listed in the recipe routing module will reroute the user to the wild card path, to your PageNotFoundComponent.
Great solution tho.
I solved the problem lazy loading all the routes and then adding the PageNotFound route '**' at the end, hope this helps anyone that faced the same problem:
import { Routes, RouterModule } from '#angular/router';
import { NgModule } from '#angular/core';
import { PageNotFoundComponent } from './errors/page-not-found/page-not-found.component';
// If new and :id children were inverted that would make angular take new as id
// ant that would break the app, the order of the routes is very important
// that's why the 404 PageNotFoundComponent goes the last one
const appRoutes: Routes = [
{ path: '', redirectTo: 'recipes', pathMatch: 'full' },
{ path: 'recipes', loadChildren: () => import('./recipes/recipes.module').then(m => m.RecipesModule) },
{ path: 'shopping-list', loadChildren: () => import('./shopping-list/shopping-list.module').then( m => m.ShoppingListModule) },
{ path: 'auth', loadChildren: () => import('./auth/auth.module').then( m => m.AuthModule) },
{ path: '**', component: PageNotFoundComponent }
];
#NgModule({
imports: [RouterModule.forRoot(appRoutes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}

angular 2 router is not working on iphone device i have build using cordova

I have createsimple angular2 project make ios build using cordova but my default router is not loading on iOS device it is working fine on browser and android device.Below is the my app-routing.module.ts and also i have set the base href="/" in index.html file
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { DashboardComponent } from './dashboard.component';
import { HeroesComponent } from './heroes.component';
import { HeroDetailComponent } from './hero-detail.component';
const routes: Routes = [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'detail/:id', component: HeroDetailComponent },
{ path: 'heroes', component: HeroesComponent }
];
#NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
Do this
base href="."
this will work
Actually, cordova with angular 2+, this is what worked for me:
<base href="">
So just empty href.

Angular 2 ES6 - Sending event from component

I want to send an custom event from Component in ES6, so I can listen to it in template <component (someEvent)="someFunction()">, but i cannot make it happen.
#Component's properties ouputs or events are breaking the application. Am I missing something?
this is my Component declaration:
import {Component, Output} from 'angular2/core';
#Component({
selector: 'section-navigator-component',
templateUrl: 'build/components/section_navigator/section_navigator.html',
inputs: [ 'resources', 'attr' ],
outputs: [ 'someEvent' ]
})
export class SectionNavigatorComponent {
constructor() {
}
resourceClickHandler($event, resource) {
}
}
This should work in your case:
import {Component, Output, EventEmitter} from 'angular2/core';
#Component({
selector: 'section-navigator-component',
templateUrl: 'build/components/section_navigator/section_navigator.html',
inputs: [ 'resources', 'attr' ],
outputs: [ 'someEvent' ]
})
export class SectionNavigatorComponent {
constructor() {
this.someEvent = new EventEmitter();
}
resourceClickHandler($event, resource) {
this.someEvent.emit(someValue);
}
}
You do not need to import 'Output' unless you use the alternate TypeScript syntax below:
import {Component, Input, Output, EventEmitter} from 'angular2/core';
#Component({
selector: 'section-navigator-component',
templateUrl: 'build/components/section_navigator/section_navigator.html'
})
export class SectionNavigatorComponent {
#Input() resources: any;
#Input() attr: any;
#Output() someEvent: EventEmitter<any> = new EventEmitter();
constructor() {
}
resourceClickHandler($event, resource) {
this.someEvent.emit(someValue);
}
}