Angular Routes are not working in Angular 12 - html

I created a web application in Angular in which i have components, the login component and register component. Each time i add the element routerLink to the <a...> in order for me to navigate from one component to another, it doesn't work. It turns the text or nav item into a read-only text.
The funny thing is that if i change it from "routerLink" to "href", the text/nav item becomes active. I really don't understand why this is happening. I have followed every suggestion made in this forum similar to this but none actually work when i tried them. I also followed suggestions written on the Angular.io website. It is still the same. i also imported RouterModule into my app.module.ts. It hasn't worked as we speak. I am using Angular/CLI 12.2.0, Bootstrap 5, and Typescript 4. Below is my code
<!-- Navbar-->
<nav
class="
navbar navbar-transparent navbar-color-on-scroll
fixed-top
navbar-expand-lg
"
color-on-scroll="100"
id="sectionsNav"
>
<div class="container-fluid">
<div class="navbar-translate">
<a routerLink="#" class="navbar-brand">
<img
src="../../../assets/img/comgreen.png"
width="50"
height="50"
alt=""
class="d-inline-block"
/>
<strong>Comgreen</strong></a
>
<button
class="navbar-toggler"
type="button"
data-bs-toggle="collapse"
data-bs-target="#navbar"
aria-controls="navbar"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span class="sr-only">Toggle navigation</span>
<span class="navbar-toggler-icon"></span>
<span class="navbar-toggler-icon"></span>
<span class="navbar-toggler-icon"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="navbar">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a
routerLink="/login"
routerLinkActive="active"
class="nav-link"
rel="tooltip"
title=""
data-placement="bottom"
target=""
data-original-title="Log in with your credentials"
>
<i class="material-icons">fingerprint</i>Login
</a>
</li>
<li class="nav-item">
<a
routerLink="/user-register"
routerLinkActive="active"
class="nav-link"
rel="tooltip"
title=""
data-placement="bottom"
target=""
data-original-title="Don't have an account? Register"
>
<i class="fa fa-user-plus"></i>Register
</a>
</li>
<li class="nav-item">
<a
class="nav-link"
rel="tooltip"
title=""
data-placement="bottom"
target="_blank"
data-original-title="Follow us on Twitter"
rel="nofollow"
>
<i class="fa fa-twitter"></i>
</a>
</li>
<li class="nav-item">
<a
class="nav-link"
rel="tooltip"
title=""
data-placement="bottom"
routerLink="/hero"
target="_blank"
data-original-title="Like us on Facebook"
rel="nofollow"
>
<i class="fa fa-facebook-square"></i>
</a>
</li>
<li class="nav-item">
<a
class="nav-link"
rel="tooltip"
title=""
data-placement="bottom"
routerLink="/hero"
target="_blank"
data-original-title="Follow us on Instagram"
rel="nofollow"
>
<i class="fa fa-instagram"></i>
</a>
</li>
</ul>
</div>
</div>
</nav>
<!--End of Navbar-->
My app.module.ts file:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { HttpClientModule } from '#angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {RouterModule } from '#angular/router';
import { FooterComponent } from './shared/footer/footer.component';
import { MatFormFieldModule } from '#angular/material/form-field';
import { MatInputModule } from '#angular/material/input';
import { MatButtonModule } from '#angular/material/button';
import { MatCheckboxModule } from '#angular/material/checkbox';
import { MatMenuModule } from '#angular/material/menu';
import { BrowserAnimationsModule } from '#angular/platform-browser/animations';
import { SidebarComponent } from './sidebar/sidebar.component';
import { NavbarComponent } from './shared/navbar/navbar.component';
import { MsgiconbtnComponent } from './shared/msgiconbtn/msgiconbtn.component';
import { SettingsService } from './services/settings.service';
import { HomeComponent } from './dashboard/home/home.component';
import { CropComponent } from './dashboard/crop/crop.component';
import { FarmersComponent } from './dashboard/farmers/farmers.component';
import { InsuranceComponent } from './dashboard/insurance/insurance.component';
import { ImagecardComponent } from './shared/imagecard/imagecard.component';
import { AddNewCropDialogModule } from './shared/dialog/add-new-crop-dialog/add-new-crop-dialog.module';
import { AddNewFarmerDialogModule } from './shared/dialog/add-new-farmer-dialog/add-new-farmer-dialog.module';
import { AngularFirestoreModule } from '#angular/fire/firestore';
import { AngularFireAuthModule } from '#angular/fire/auth';
import { AngularFireModule } from '#angular/fire';
import { environment } from 'src/environments/environment';
import { AngularFireStorageModule } from '#angular/fire/storage';
import { MorecropinfoModule } from './shared/dialog/morecropinfo/morecropinfo.module';
import { UpdateCropInfoModule } from './shared/dialog/update-crop-info/update-crop-info.module';
import { SplashComponent } from './pages/splash/splash.component';
import { HeaderComponent } from './shared/header/header.component';
import { ReactiveFormsModule } from '#angular/forms';
import { userRegisterComponent } from './pages/userregister/userRegister.component';
import { VerifyEmailComponent } from './pages/verify-email/verify-email.component';
import { ForgotPasswordComponent } from './pages/forgot-password/forgot-password.component';
import { LoginComponent } from './pages/login/login.component';
import { RegisterUserComponent } from './pages/register-user/register-user.component';
#NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
SidebarComponent,
NavbarComponent,
MsgiconbtnComponent,
HomeComponent,
CropComponent,
FarmersComponent,
InsuranceComponent,
ImagecardComponent,
SplashComponent,
userRegisterComponent,
LoginComponent,
VerifyEmailComponent,
ForgotPasswordComponent,
userRegisterComponent,
RegisterUserComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule,
MatFormFieldModule,
RouterModule,
MatInputModule,
MatButtonModule,
MatCheckboxModule,
MatMenuModule,
HttpClientModule,
MorecropinfoModule,
AddNewCropDialogModule,
AddNewFarmerDialogModule,
UpdateCropInfoModule,
BrowserAnimationsModule,
AngularFirestoreModule,
AngularFireAuthModule,
AngularFireStorageModule,
AngularFireModule.initializeApp(environment.firebaseConfig)
],
providers: [SettingsService],
bootstrap: [AppComponent]
})
export class AppModule { }
Where am i going wrong?

I don't know if it would make a difference but in my project I moved the routerLinkActive = "active" to the html li tag.
Maybe it does also work for you...
<li class="nav-item"
routerLinkActive="active">
<a
routerLink="/login"
class="nav-link"
rel="tooltip"
title=""
data-placement="bottom"
target=""
data-original-title="Log in with your credentials"
>
<i class="material-icons">fingerprint</i>Login
</a>
</li>

Try with square brackets, just like it was array of path elements:
<a [routerLink]="['/user-register']">Link</a>
Then if you want deeper it would look like this:
// const userId = '12345';
<a [routerLink]="['/user', 'profile', userId]">Link</a>
This will redirect you to localhost:4200/user/profile/12345
And if we are talking about style of link, like underline/color change on hover, just use some css:
a {
color: black;
cursor: pointer;
}
a:hover {
color: red;
text-decoration: underline;
} // ...etc whatever you need

Related

Angular, not able to redirect to another web page

first of all thank you very much for taking the time to read this consultation. I'm new to angular development, I found it interesting to learn about this technology and not use the frameworks I've been using for some time. Currently I'm developing a very simple web application, the problem I have is that when I click on the "Login" link absolutely nothing happens. It also doesn't show me an error message. I copy the code that I currently have. I thank you if you could help me with this problem.
app.component.html
<nav class="navbar navbar-expand navbar-dark bg-dark fixed-top">
<div class="navbar-collapse collapse w-100 order-3 dual-collapse2">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link js-scroll-trigger" href="#">Inicio</a>
</li>
....
<li class="nav-item">
<!-- <a class="nav-link" [routerLink]="['/login']">Iniciar Sesión</a> -->
<a class="nav-link" routerLink="/login">Iniciar Sesión</a>
</li>
</ul>
</div>
</nav>
app.module.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { ReactiveFormsModule } from '#angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '#angular/common/http';
// used to create fake backend
import { fakeBackendProvider } from './_helpers';
import { appRoutingModule } from './app.routing';
import { JwtInterceptor, ErrorInterceptor } from './_helpers';
import { AppComponent } from './app.component';
import { HomeComponent } from './home';
import { LoginComponent } from './login';
import { RegisterComponent } from './register';
import { AlertComponent } from './_components';
#NgModule({
imports: [
BrowserModule,
ReactiveFormsModule,
HttpClientModule,
appRoutingModule
],
declarations: [
AppComponent,
HomeComponent,
LoginComponent,
AboutComponent,
TeamComponent,
ServiceProvidedComponent,
ContactComponent,
RegisterComponent,
AlertComponent
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
// provider used to create fake backend
fakeBackendProvider
],
bootstrap: [AppComponent]
})
export class AppModule { };
app.components.ts
import { Component } from '#angular/core';
import { Router} from '#angular/router';
import { AuthenticationService } from './_services';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
currentUser: any;
constructor(private router: Router, private authenticationService: AuthenticationService) {
this.router.errorHandler = (error: any) => {
this.router.navigate(['404']); // or redirect to default route
};
this.authenticationService.currentUser.subscribe(x => this.currentUser = x);
}
logout() {
this.authenticationService.logout();
this.router.navigate(['/login']);
}
}
app.routing.ts
import { Routes, RouterModule } from '#angular/router';
import { HomeComponent } from './home';
import { LoginComponent } from './login';
import { RegisterComponent } from './register';
import { AuthGuard } from './_helpers';
const routes: Routes = [
// { path: '', component: HomeComponent, canActivate: [AuthGuard] },
{ path: '', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{ path: 'register', component: RegisterComponent },
// otherwise redirect to home
// { path: '**', redirectTo: '' }
];
export const appRoutingModule = RouterModule.forRoot(routes);
You need the <router-outlet></router-outlet> to show the rendered views.
So your code should be
<nav class="navbar navbar-expand navbar-dark bg-dark fixed-top">
<div class="navbar-collapse collapse w-100 order-3 dual-collapse2">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link js-scroll-trigger" href="#">Inicio</a>
</li>
....
<li class="nav-item">
<!-- <a class="nav-link" [routerLink]="['/login']">Iniciar Sesión</a> -->
<a class="nav-link" routerLink="/login">Iniciar Sesión</a>
</li>
</ul>
</div>
</nav>
<router-outlet></router-outlet>

My button loads a page underneath the current page

I have created a button in a html file inside an Angular component. When I click on the button it loads the page underneath the current page and making a single long page, instead of showing a new page. How do I solve this?
<button type="button" class="btn m-1 btn btn-success w-100" (click)="btnClick();"><i class="fa fa-plus"></i>Open page</button>
btnClick= function () {
this.router.navigateByUrl('/testcomponent');
};
<div class="container mt-5">
<div class="row">
<div class="col-sm col-md-4">
<div class="card mb-4">
<div class="card-body">
<h5 class="card-title text-center">OPTIONS</h5>
<p class="card-text">
<button type="button" class="btn m-1 btn btn-success w-100" (click)="btnClick();"><i class="fa fa-plus"></i>Open page</button>
</p>
</div>
</div>
</div>
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpClientModule } from '#angular/common/http';
import { FormsModule } from '#angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { TestComponent} from './testcomponent/testcomponent.component';
import { RouterModule, Routes } from '#angular/router';
const appRoutes: Routes = [
{ path: 'testcomponent', component: TestComponent },
];
#NgModule({
declarations: [
AppComponent,
HeaderComponent,
TestComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
FormsModule,
RouterModule.forRoot(
appRoutes,
{ enableTracing: true } // <-- debugging purposes only
)
// other imports here
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<a [routerLink]="['/testcomponent']">Open page</a> or Open page for more information
please refer this https://angular.io/guide/router

Can't navigate to other components in angular 7

I have an angular project with 3 components namely:- Search,View,Insert, each component have their own routing-module and module.ts files.
However the issue is I am not able to navigate from Search to View or Insert by clicking on Sidebar Option. However if I create a button and use this.router.navigateByUrl('/view'); then I am able to go to View Page.
Similarly in Insert Page also I am having same issue.
Project Structure:
Layout Routing File:-
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { LayoutComponent } from './layout.component';
const routes: Routes = [
{
path: '',
component: LayoutComponent,
children: [
{
path: '',
redirectTo: 'search',
pathMatch: 'prefix'
},
{
path: 'search',
loadChildren: './search/search.module#SearchModule'
},
{
path: 'view',
loadChildren: './view/view.module#ViewModule'
},
{
path: 'insert',
loadChildren: './insert/insert.module#InsertModule'
},
]
}
];
#NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class LayoutRoutingModule { }
app.module.ts
import { CommonModule } from '#angular/common';
import { HttpClientModule } from '#angular/common/http';
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { BrowserAnimationsModule } from '#angular/platform-
browser/animations';
import { LanguageTranslationModule } from './shared/modules/language-
translation/language-translation.module';
import { AngularMaterialModule } from '../app/angular-material.module';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AuthGuard } from './shared';
import {MatFormFieldModule, MatSelectModule, MatInputModule,
MatButtonModule} from '#angular/material';
import { CustomHttpService } from '../app/shared/services/custom-
http.service';
import { UserService } from './shared/services/user.service';
#NgModule({
imports: [
CommonModule,
BrowserModule,
BrowserAnimationsModule,
HttpClientModule,
LanguageTranslationModule,
AppRoutingModule,
MatFormFieldModule,
MatSelectModule,
MatInputModule,
MatButtonModule,
AngularMaterialModule
],
declarations: [AppComponent],
providers: [AuthGuard, CustomHttpService, UserService],
bootstrap: [AppComponent]
})
export class AppModule {
}
Sidebar.component.html
<nav class="sidebar" [ngClass]="{ sidebarPushRight: isActive, collapsed:
collapsed }">
<div class="list-group">
<a routerLink="/search" [routerLinkActive]="['router-link-active']"
class="list-group-item">
<i class="fa fa-fw fa-search"></i>
<span>{{ 'Search' }}</span>
</a>
<a routerLink="/dashboard" [routerLinkActive]="['router-link-active']"
class="list-group-item">
<i class="fa fa-eye" aria-hidden="true"></i>
<span>{{ 'Dashboard' }}</span>
</a>
<a routerLink="/dashboard" [routerLinkActive]="['router-link-active']"
class="list-group-item">
<i class="fa fa-pencil-square-o" aria-hidden="true"></i>
<span>{{ 'Insert' }}</span>
</a>
</nav>
Try like this
<a [routerLink]="['/dashboard']"
class="list-group-item">
<i class="fa fa-eye" aria-hidden="true"></i>
<span>{{ 'Dashboard' }}</span>
</a>
for more information refer this https://angular.io/api/router/RouterLink#description
Try replacing [routerLinkActive]="['router-link-active'] with [routerDirection]="'root'" in your Sidebar.component.html file
<a routerLink="/search" [routerDirection]="'root'"
class="list-group-item">
<i class="fa fa-fw fa-search"></i>
<span>{{ 'Search' }}</span>
</a>

Added Bootstrap header and now the component is duplicating

I have added a Navbar from Bootstrap to a React App and for some reason, it is duplicating when I render the app. Not sure what is happening. Here is the code from below is my headercomponent.
import React, { Component } from 'react';
import Navbar from './Navbar.jsx';
class HeaderName extends Component {
render() {
return (
<div>
<div>
<Navbar />
</div>
<h1>The AquaStars New Website.</h1>
<img src="../public/images/picture_swimmers.png" />
</div>
)
}
}
export default HeaderName;
Below is the Navbar.jsx component.
import React,{ Component } from 'react';
import { Link } from 'react-router-dom';
import './Navbar.css';
class Navbar extends Component {
render() {
return (
<nav className="navbar navbar-expand-md navbar-dark bg-dark mb-4">
<a className="navbar-brand" href="#">Top navbar</a>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarCollapse">
<ul className="navbar-nav mr-auto">
<li className="nav-item active">
<a className="nav-link" href="#">Home <span className="sr-only">(current)</span></a>
</li>
<li className="nav-item">
<a className="nav-link" href="#">Link</a>
</li>
<li className="nav-item">
<a className="nav-link disabled" href="#">Disabled</a>
</li>
</ul>
</div>
</nav>
);
}
}
export default Navbar;
Below is the index.js. This is where I think the problem is.
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom'
import HeaderName from './components/header';
import FooterName from './components/footer';
import DescripTitle from './components/descrip';
import DescripName from './components/intro';
//create a new componet. Produce some HTML.
// const App = function() {
// return <div>Welcome to Aquastars Website</div>;
// }
const App = () => {
return (
<div>
<Router>
<div>
<Route exact path="/" component={HeaderName}/>
</div>
</Router>
<HeaderName />
<DescripName />
<DescripTitle />
<FooterName />
</div>
);
}
//Take this component's generated HTML and put it
// on the page(in the DOM).
ReactDOM.render(<App />, document.querySelector('.container'));
Any help would be appreciated.
Make sure you are not rendering the Navbar component in your app.js/index.js or wherever the headerName component is being imported. Can you post these files as well? What is inside the Navbar component. More information is needed.
-EDIT-
You can make a new Component that brings In any page contents into a "page component" then in your render:
<HeaderName/>
<Router exact path="/somedirectory" component{yourPageComponent}/>
<FooterName/>
This will make sure that header and footer are rendered on every page but only certain content is rendered on route changes. Cheers.

Angular 4 switch with different components

I'm trying to make my menu load according to the click on the "Cadastros" action but I believe the problem is the "workspaceSelected" property that is not visible to all components.
I believe the correct location for this case would be the property "workspaceSelected" being in the component sidenav, but I do not know how to handle this type of situation.
I would like to click on the action "Cadastros" and she make the switch to load the correct html component.
principal component class:
export class PrincipalComponent implements OnInit {
workspaceSelecionada: string;
constructor() { }
ngOnInit() {
}
}
Principal component:
<header>
<app-navbar></app-navbar>
<app-sidenav></app-sidenav>
</header>
<div class="container" [ngSwitch]="workspaceSelecionada">
<app-cadastros *ngSwitchCase="'cadastros'"></app-cadastros>
<app-movimentacoes *ngSwitchCase="'movimentacoes'"></app-movimentacoes>
<app-administracao *ngSwitchCase="'administracao'"></app-administracao>
<app-relatorios *ngSwitchCase="'relatorios'"></app-relatorios>
<app-configuracoes *ngSwitchCase="'configuracoes'"></app-configuracoes>
<app-dashboard *ngSwitchDefault></app-dashboard>
</div>
app-sidenav:
<!--SideNav-->
<ul id="slide-out" class="side-nav grey darken-2">
<li>
<div class="userView">
<div class="background">
<img src="images/office.jpg">
</div>
<img class="circle" src="images/yuna.jpg">
<span class="white-text name">John Doe</span>
<span class="white-text email">jdandturk#gmail.com</span>
</div>
</li>
<li>
<a (click)="workspaceSelecionada = 'cadastros'" class="btn-large waves-effect waves-light indigo darken-3">CADASTROS</a>
</li>
<li>
<a class="btn-large waves-effect waves-light purple darken-3">MOVIMENTAÇÕES</a>
</li>
<li>
<a class="btn-large waves-effect waves-light orange darken-3">ADMINISTRAÇÃO</a>
</li>
<li>
<a class="btn-large waves-effect waves-light yellow darken-3">RELATÓRIOS</a>
</li>
<li>
<a class="btn-large waves-effect waves-light light-green darken-3">CONFIGURAÇÕES</a>
</li>
</ul>
<a data-activates="slide-out" class="button-collapse"><i class="material-icons">menu</i></a>
As suggested above in the comment, define a routing module for the application:
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import {CadastrosComponent} from './...component';
....
const appRoutes: Routes = [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'cadastros', component: CadastrosComponent}
];
#NgModule({
imports: [RouterModule.forRoot(appRoutes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
Then import the routing module in your app module:
imports: [AppRoutingModule]
Then instead of switch case statement in your principal component, define the router outlet as below:
<router-outlet></router-outlet>
Then in the anchor tag in your side nav component template, define the router link as below:
<a routerLink="/cadastros">CADASTROS</a>
Hope this helps! Do let me know if you face any challenges implementing it.