Im trying to redirect my page from login to another page. Im following this code.
My login component ts file:
import { Router } from '#angular/router';
constructor(private router: Router) {
}
funLogin(mobilenumber){
this.router.navigateByUrl('registration');
}
In my html Im calling this function in a submit btn,
<button class="common-btn btn" (click)="funLogin(mobileNo.value)">Submit</button>
In my app.login.routing file,
export const loginRouting: Routes = [
{
path: '', component: DashboardRootComponent, canActivateChild: [],
children: [
{ path: '', component: DashboardComponent, pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'registration', component: RegistrationComponent },
]
}
]
I have tried with "this.router.navigate" & referredlot of links. But it didnt work. Can anyone please tell me where Im going wrong or if you could give me a workingh sample it would be better.
#sasi.. try like this,
<a routerLink="/registration"><button class="btn btn-success" > Submit </button></a>
Update :
In order to use the routing in your application, you must register the components which allows the angular router to render the view.
We need register our components in App Module or any Feature Module of it (your current working module) in order to route to specific component view.
We can register components in two ways
.forRoot(appRoutes) for app level component registration like
featuteModules(ex. UserManagement) and components which you want register at root level.
.forChild(featureRoutes) for feature modules child components(Ex. UserDelete, UserUpdate).
you can register something like below,
const appRoutes: Routes = [
{ path: 'user', loadChildren: './user/user.module#UserModule' },
{ path: 'heroes', component: HeroListComponent },
];
#NgModule({
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot(
appRoutes
)
],
P.S : In order to navigate from one component to another, you must include the RouterModule in corresponding Module Imports array from #angular/router package.
You can navigate one to another page in Angular in Two ways. (both are same at wrapper level but the implementation from our side bit diff so.)
routerLink directive
routerLink directive gives you absolute path match like navigateByUrl() of Router class.
<a [routerLink]=['/registration']><button class="btn btn-success" > Submit </button></a>
If you use dynamic values to generate the link, you can pass an array of path segments, followed by the params for each segment.
For instance routerLink=['/team', teamId, 'user', userName, {details: true}] means that we want to generate a link to /team/11/user/bob;details=true.
There are some useful points to be remembered when we are using routerLink.
If the first segment begins with /, the router will look up the route
from the root of the app.
If the first segment begins with ./, or doesn't begin with a slash,
the router will instead look in the children of the current activated
route.
And if the first segment begins with ../, the router will go up one
level.
for more info have look here.. routerLink
Router class
We need inject Router class into the component in order to use it's methods.
There more than two methods to navigate like navigate() , navigateByUrl(), and some other.. but we will mostly use these two.
navigate() :
Navigate based on the provided array of commands and a starting point. If no starting route is provided, the navigation is absolute.
this.route.navigate(['/team/113/user/ganesh']);
navigate() command will append the latest string is append to existing URL. We can also parse the queryParams from this method like below,
this.router.navigate(['/team/'], {
queryParams: { userId: this.userId, userName: this.userName }
});
You can get the these values with ActivatedRoute in navigated Component. you can check here more about paramMap, snapshot(no-observable alternative).
navigateByUrl()
Navigate based on the provided URL, which must be absolute.
this.route.navigateByUrl(['/team/113/user/ganesh']);
navigateByUrl() is similar to changing the location bar directly–we are providing the whole new URL.
I am using angular 7 and I solved it in this way into my project.
1.First We need to implement this Modules to our app.module.ts file
import { AppRoutingModule} from './app-routing.module';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
#NgModule({
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
],
})
2.Then Open your.component.html file and then fire a method for navigate where you want to go
<button class="btn btn-primary" (click)="gotoHome()">Home</button>
3.Then Go your.component.ts file for where you want to navigate. And add this code there.
import { Router } from '#angular/router';
export class YourComponentClassName implements OnInit {
constructor(private router: Router) {}
gotoHome(){
this.router.navigate(['/home']); // define your component where you want to go
}
}
4.And lastly want to say be careful to look after your app-routing.module.ts
where you must have that component path where you want to navigate otherwise it will give you error. For my case.
const routes: Routes = [
{ path:'', component:LoginComponent},
{ path: 'home', component:HomeComponent }, // you must add your component here
{ path: '**', component:PageNotFoundComponent }
];
Thanks I think, I share all of the case for this routing section. Happy Coding !!!
navigateByUrl expects an absolute path, so a leading / might take you to the right page
You could also use navigate and don't need the leading / but the syntax is slightly different as it expects an array for the path
https://angular.io/api/router/Router#navigateByUrl
<a class="nav-link mt-1" [routerLink]="['/login']"><i class="fa fa-sign-in"></i> Login</a>
Related
I'm trying to make a router for one of my components, but it is not working as expected.
Initially it was working fine, but I had to add another route to decide which mat-tab would be open when redirecting. I added the second route like that, but for some reason the third one stopped working even though the first two were working fine.
import { Routes } from '#angular/router';
import { ActionComponent } from './action.component';
import { ActionResolver } from './action.resolver';
import { ACTION_RESULT_ROUTES } from './result/action-result.routes';
export const ACTION_ROUTES: Routes = [
{ path: ':id', component: ActionComponent, resolve: { action: ActionResolver } },
{ path: ':id/:tab', component: ActionComponent, resolve: { action: ActionResolver } },
{
path: 'action-result',
children: ACTION_RESULT_ROUTES,
},
];
I got a pretty large error when trying the third route, but it starts like this:
ERROR Error: Uncaught (in promise): TypeError: You provided 'null' where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.
Just in case, I tried to reorder it and all three were working fine when I did it like this:
export const ACTION_ROUTES: Routes = [
{ path: ':id', component: ActionComponent, resolve: { action: ActionResolver } },
{
path: 'action-result',
children: ACTION_RESULT_ROUTES,
},
{ path: ':id/:tab', component: ActionComponent, resolve: { action: ActionResolver } },
];
Can anyone tell me why it works like that?
Edit: Added the ACTION_RESULT_ROUTES for clarification
export const ACTION_RESULT_ROUTES: Routes = [
{ path: ':id', component: ActionResultComponent, resolve: { result: ActionResultResolver } },
];
According to Angular:
"The order of routes is important because the Router uses a
first-match wins strategy when matching routes, so more specific
routes should be placed above less specific routes."
It is recommended to have static routes first, therefore your action-result path should go first, followed by the :id/:tab path then :id path last. If you have a wildcard route, it should always be the last route in your array.
The reason behind this logic is that if you had the :id path above the action-result path, angular would use the word 'action-result' as the id in the :id path.
Similarly if you had the :id path above the :id/:tab path, angular would use the words id/tab as the id in the :id path.
So, a rule of thumb is to always put your static routes first, then your dynamic routes from the most specific to the least specific followed by your wildcard route at the end.
E. G.
PATH1
PATH2
PATH3/:USER/:ROLE/:PAGE
PATH4/:SITE/:ID
PATH5:/ID
Wildcard route (*)
I'm currently trying to implement Lottie to my Angular web-app.
Somehow I couldn't manage to do so yet. I tried to follow the instructions from github, but that lead to multiple errors, as f.e.:
lottie-player is not a known ng module.
Furthermore, I tried to install ng-lottie for Angular - since the original wasn't working - but this one didn't provide any option to jump to a frame or loop only to a certain frame.
Does anyone know an alternative or a way to get lottie player working?
You can add lottie-player as a custom element schema
npm install --save #lottiefiles/lottie-player
angular.json
"scripts": [
"./node_modules/#lottiefiles/lottie-player/dist/lottie-player.js"
]
custom.module.ts
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '#angular/core';
#NgModule({
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class CustomModule { }
custom.component.html
<lottie-player src="https://assets4.lottiefiles.com/datafiles/zc3XRzudyWE36ZBJr7PIkkqq0PFIrIBgp4ojqShI/newAnimation.json" background="transparent" speed="1" loop autoplay >
</lottie-player>
Hope this helps! and if you managed to implements it with a different approach you can help by sharing it
theres a much simpler approach, install required packages as below
npm i ngx-lottie & lottie-web
in your app.module.ts, add
import { LottieModule } from 'ngx-lottie'; // add this line
export function playerFactory() { // add this line
return import('lottie-web'); // add this line
} // add this line
#NgModule({
declarations: ['your component 1', 'your component 2'...],
imports: [
LottieModule.forRoot({ player: playerFactory, useCache: true }) // add this line
]})
stop your angular server 4200 and start again using ng serve
define options in your component.ts file as
options: AnimationOptions = {
path: 'add animation json file link', // download the JSON version of animation in your project directory and add the path to it like ./assets/animations/example.json
};
then in your component.ts file
import the animation options module at the top of your component as
import { AnimationOptions } from 'ngx-lottie';
then in your component.html
<ng-lottie height="auto" [options]="options"></ng-lottie>
for more information on other attributes of ng-lottie tag visit
https://www.npmjs.com/package/ngx-lottie
I had created one project for login form, here am attaching screenshot of program,
while am executing my project it is showing only index page and waited for some time but still showing only index page, here am attaching output screenshot,
If you want to display a login page as a default page when user serves the application then you have to configure your app.module.ts to handle these type of URL. So the changes that you required is as:
In app.module.ts:
Import RouterModule from angular/router:
import { RouterModule } from '#angular/router';
and in imports Array add
RouterModule.forRoot([
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent }
])
and in app.component.html:
<router-outlet></router-outlet>
That’s because when we run ng-serve to start up our server it creates JavaScript bundles and automatically adds the right imports into our index.html.
In order for your app.component.html to show in localhost:4200, add <router-outlet></router-outlet? to your index.html.
Problem
I have 4 static pages with full angular 6 web app I want to render home.html page on start and after login redirect to actual angular web app from where angular routing fired up and do the magic. question is why I want this? I want this because my web app have some static pages like home, contact us,I want terms and conditions and privacy policy etc. I want this pages to be static for crawler friendly and also for fast rendering by excluding angular out of it.
Question
How I can achieve this.
Done so far
I create 3 static pages in root where index.html is located. the in angular cli I put this line
"index": "src/home.html",
but now I an unable to navigate to contactus.html page it shows me this error.
Error
"The selector "app-root" did not match any elements"
If I understand you right, you can use "Routes" for mapping your page and show in the same "index" all your contend easily. Is versatile, because with that, you can manage lot of things like the session access: I show you an example:
app.module.ts
import { Routes, RouterModule } from '#angular/router';
/*Example component*/
import { InicioComponent } from './inicio/inicio.component';
import{ ExamplePage } from './page1/examplePage.component';
/*Routes mapping*/
const routes: Routes = [
{path: '', component: InicioComponent },
{path: 'proveedores', component: ExamplePage, canActivate: [GuardService] }] /* Example of protected by session page*/
#NgModule({
declarations: [
ExamplePage,
InicioComponent
],
imports: [
RouterModule.forRoot(routes)
]
app.component.html
<h1>Angular</h1>
<hr>
<hr>
<app-header></app-header>
<div class="container text-center">
<router-outlet>**Here are all the pages**</router-outlet>
</div>
This is only a short example, is complicated do a deep explain of that here, but there are a lot of documentation in angular.io about this module: https://angular.io/guide/router
I have three named router outlets as shown below.
...
<router-outlet name="menus"><router-outlet>
<router-outlet><router-outlet>
<router-outlet name="footer"><router-outlet>
...
In the markup I want to route the first one, menus, to a component with certain submenu junk in it as shown in the docs.
<ul *ngFor="let main of menus;"
routerLink="[{outlets:{menus:[{{main.link}}]}}]"
class="nav-items">{{main.header}}
The error I'm getting says that:
Error: Cannot match any routes. URL Segment: '%5B%7Boutlets:%7Bmenus:%5Bsubmenu1%5D%7D%7D%5D'
Am at a loss what's wrong with the syntax. Googling my fingernails off but haven't found a simple and crude example of a routerLink version showing how to point a route in a named outlet.
Edit: Based on the comments and samples, I need to reformulate the code being used, still with the same error. In the markup:
<ul *ngFor="let main of menus;"
(click)="pullMenu(main.link)"
class="nav-items">{{main.header}}
Then, in TS:
constructor(private router: Router, private route: ActivatedRoute) { }
pullSubmenu(input) {
console.log(input);
this.router.navigate(
[{ outlets: { menus: [input] } }],
{ relativeTo: this.route });
}
Now, I'm getting the following error (submenu1 is the name of configured path).
Error: Cannot match any routes. URL Segment: 'submenu1'
My routing is set up in the module like this.
const routes: Routes = [
{ path: "submenu1", component: Submenu1Component },
{ path: "submenu2", component: Submenu2Component }
];
#NgModule({
declarations: [
AppComponent,
NavbarComponent,
MainAreaComponent,
Submenu1Component,
Submenu2Component
],
imports: [
BrowserModule,
RouterModule.forRoot(routes)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
You need to use the evaluated version [routerLink]:
<ul *ngFor="let main of menus;"
[routerLink]="[{outlets:{menus:[{{main.link}}]}}]"
class="nav-items">{{main.header}}
As an alternative you can emulate the routerLink. Here is the gist of what it does:
#HostListener('click')
onClick(): boolean {
const extras = {
skipLocationChange: attrBoolValue(this.skipLocationChange),
replaceUrl: attrBoolValue(this.replaceUrl),
};
this.router.navigateByUrl(this.urlTree, extras);
return true;
}
So, here is the setup using navigate instead of navigateByUrl:
#Component({
template: `
<ul *ngFor="let main of menus;" (click)="[{outlets:{menus:[{{main.link}}]}}])"
class="nav-items">{{main.header}}
`
...
class MyComponent {
constructor(router: Router, route: ActivatedRoute) {}
navigate(commands) {
this.router.navigate(commands, {relativeTo: this.route})
You can't use unevaluated version of routerLink because it reads commands as a string and if you have outletsin the commands strings don't work. See Navigation to secondary route URL for routerLink attribute to understand why.