How to redirect to another page using angular 7

Asked

Viewed 3,867 times

1

I am making an application using angular 7 with angular/cli, but I find myself in a problem, I finished my login screen and I want to redirect to Dashboard;

But I find where the router-outlet opens the file inside the app component, I wanted to know a way to open another html page, even if it was another module.

<div class="row">
    <!-- divisão das colunas -->
    <div class="col-md-4">

        <!-- seletor de idiomas -->
        <div class="dropdown" style="float:right">
            <button id="btn-SelecaoIdioma" type="button"
                class="btn btn-link dropdown-toggle default-link-login login-link-idioma" data-toggle="dropdown">
                Português (Brasil)
            </button>
            <div class="dropdown-menu" aria-labelledby="dropdownMenu2" style="font-size: 14px;">
                <button class="dropdown-item" type="button"><a href="/Account/Language/en-US">English (United
                        States)</a></button>
                <button class="dropdown-item" type="button"><a href="/Account/Language/es">Español</a></button>
                <button class="dropdown-item active" type="button"><a href="/Account/Language/pt-BR">Português
                        (Brasil)</a></button>
            </div>
        </div>

        <!-- div da imagem -->

        <div id="login-logo" >

            <img src="../assets/Images/Logo-solucao.png" 
                class="img-logo-login img-responsive">

        </div>

        <router-outlet></router-outlet>


        <footer class="alinhar-footer" id="footer-login">
            <div class="justify-content-center">
                <!-- linha de layout -->

                <hr class="my-3">

                <!-- acesso por credenciais de terceiros -->
                <div>
                    <p class="text-center">Ou use suas Credenciais </p>
                </div>
                <div class="row-social justify-content-center">

                    <div class="col-auto text-center">
                        <img id="img-Windows" class="l-social" src="../assets/Images/win.png"></div>
                    <div class="col-auto text-center">
                        <img id="img-Google" class="l-social" src="../assets/Images/google.png"></div>
                    <div class="col-auto text-center">
                        <img id="img-Facebook" class="l-social" src="../assets/Images/face.png"></div>
                    <div class="col-auto text-center">
                        <img id="img-Linkedin" class="l-social" src="../assets/Images/linkedin.png"></div>
                </div>
            </div>
            <!-- area comercial da pagina de login -->

            <p id="paragrafo-inicio" >
                Faça como diversos profissionais da área, torne-se ! <br>
                <a href="#" target="_blank" class="default-link">Fale com os nossos consultores.</a>
            </p>
            <a class="default-font-text12-login">©  - 1.0.0</a> |

            <a href="#" target="_blank" class="default-font-text12-login">Sobre o Sistema</a> |
            <a href="#" target="_blank" class="default-font-text12-login">Contato</a>
        </footer>

    </div>
    <div class="col-md-8" id="login-page">

    </div>
</div>

routing-module

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { FormLoginComponent } from './form-login/form-login.component';
import { FormRecuperarSenhaComponent } from './form-recuperar-senha/form-recuperar-senha.component';
import { FormPrincipalComponent } from './form-principal/form-principal.component';

const routes: Routes = [

  {path:'',component: FormLoginComponent},
  {path:'form-recuperar-senha',component: FormRecuperarSenhaComponent},
  {path:'form-principal',component: FormPrincipalComponent}


];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

1 answer

0

I haven’t seen you use the routerLink command inside the "a".

If that is the problem, there is a tutorial here that clarifies this part: Lazy Loading - Router Link

In a system I made, the code went like this:

<nav class="navbar navbar-dark bg-dark" data-toggle="collapse" data-target=".navbar-collapse.show">
  <a class="navbar-brand" routerLink="/">Permissões</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample01" aria-controls="navbarsExample01" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="navbar-collapse collapse" id="navbarsExample01">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item" data-toggle="collapse" data-target=".navbar-collapse.show" >
        <a class="nav-link" routerLink="/modulos">Módulos</a>
      </li>
      <li class="nav-item" data-toggle="collapse" data-target=".navbar-collapse.show" >
        <a class="nav-link" routerLink="/formularios">Formulários</a>
      </li>
      <li class="nav-item" data-toggle="collapse" data-target=".navbar-collapse.show" >
        <a class="nav-link" routerLink="/componente">Componentes</a>
      </li>
      <li class="nav-item" data-toggle="collapse" data-target=".navbar-collapse.show" >
        <a class="nav-link" routerLink="/perfil">Perfil</a>
      </li>
      <li class="nav-item" data-toggle="collapse" data-target=".navbar-collapse.show" >
        <a class="nav-link" routerLink="/funcionalidades" >Funcionalidades</a>
      </li>
      <li class="nav-item" data-toggle="collapse" data-target=".navbar-collapse.show" >
        <a class="nav-link" routerLink="/perfil-permissoes" >Perfil Permissões</a>
      </li>
    </ul>
  </div>
</nav>

<router-outlet></router-outlet>

In the file "app.routing.module.ts" it was the same as yours:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MainComponent } from './main/main.component';

const routes: Routes = [
 { path: '', component: MainComponent},
 { path: 'componente', loadChildren: './componente/componente.module#ComponenteModule' },
 { path: 'formularios', loadChildren: './formularios/formularios.module#FormulariosModule' },
 { path: 'usuario-permissoes', loadChildren: './usuario-permissoes/usuario-permissoes.module#UsuarioPermissoesModule' },
 { path: 'funcionalidades', loadChildren: './funcionalidades/funcionalidades.module#FuncionalidadesModule' },
 { path: 'modulos', loadChildren: './modulos/modulos.module#ModulosModule' },
 { path: 'perfil', loadChildren: './perfil/perfil.module#PerfilModule' },
 { path: 'perfil-permissoes',
 loadChildren: './perfil-permissoes/perfil-permissoes.module#PerfilPermissoesModule'}
];

@NgModule({
 imports: [RouterModule.forRoot(routes, {useHash: true})],
 exports: [RouterModule]
})
export class AppRoutingModule { }

Remembering that the routerLink only worked on the tags "a" with me.

EDIT: I will add a component as an example: profile.html.Component.ts

<h4 class="m-3"> Perfil</h4>
<nav class="nav">
    <a class="btn btn-success m-3" [routerLink]="['new']">Criar Perfil</a>
</nav>
<table class="table table-light mx-3 text-secondary">
  <thead class="thead-light">
    <tr>
      <th>ID</th>
      <th>Nome do Perfil</th>
      <th>Setor</th>
      <th>Sistema</th>
      <th>Descrição</th>
      <th>Ações</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td></td>
    </tr>
  </tbody>
  <tfoot>
    <tr *ngFor="let p of perfil">
      <th>{{ p.id_perfil }}</th>
      <th>{{ p.nome_perfil }}</th>
      <th>{{ p.nome_setor }}</th>
      <th>{{ p.nome_sistema }}</th>
      <th>{{ p.descricao }}</th>
      <th><a class="btn btn-sm btn-info mr-2" [routerLink]="[p.id_perfil, 'edit']">Editar</a>
        <button class="btn btn-sm btn-danger" (click)="onDelete(p.id_perfil)">Deletar</button>
      </th>

    </tr>
  </tfoot>
</table>

<ng-template #deleteModal>
  <div class="modal-body text-center">
    <p>Tem certeza que quer deletar?</p>
    <button type="button" class="btn btn-default" (click)="onConfirmDelete()">Sim</button>
    <button type="button" class="btn btn-primary" (click)="onDeclineDelete()">Não</button>
  </div>
</ng-template>

profile.componentts.

import { Component, OnInit, ViewChild } from '@angular/core';
import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';
import { Router } from "@angular/router";

import { Perfil } from '../../interface/perfil';
import { PerfilService } from '../../services/perfil.service';

@Component({
  selector: 'app-perfil',
  templateUrl: './perfil.component.html',
  styleUrls: ['./perfil.component.css']
})
export class PerfilComponent implements OnInit {

  public perfil: Perfil[];
  deleteModalRef: BsModalRef;
  deleteId: number;

  @ViewChild('deleteModal') deleteModal;

  constructor(private perfilService: PerfilService,
              private bsModalService: BsModalService,
              private router: Router) { }

  ngOnInit() {
    this.getList();
  }

  getList() {
    this.perfilService.getList().subscribe(
      (perfil: Perfil[]) => {this.perfil = perfil; },
      (error) => {console.log(error); }
    );
  }
  onDelete(id: number) {
    this.deleteId = id;
    this.deleteModalRef = this.bsModalService.show(this.deleteModal, {class: 'modal-sm'});
  }
  onConfirmDelete() {
    this.delete(this.deleteId);
    this.deleteModalRef.hide();
  }
  onDeclineDelete() {
    this.deleteModalRef.hide();
  }
  private delete(id: number) {
    this.perfilService.delete(id).subscribe(
      (response) => {console.log(response); this.getList(); },
      (error) => {console.log(error); }
    );
  }
}

profile-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { PerfilComponent } from './perfil.component';
import { PerfilFormComponent } from './perfil-form/perfil-form.component';

const routes: Routes = [
  { path: '', component: PerfilComponent },
  { path: 'new', component: PerfilFormComponent },
  { path: ':id/edit', component: PerfilFormComponent }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class PerfilRoutingModule { }

  • I understood, but he always click on the router-outlet, in your case the menu was fixed correct? and he changes the content? i wanted something similar to html window.Location.

  • Yes, the menu is always fixed at the top, you can change components that always stay fixed.

  • I edited the answer and added a component as an example

Browser other questions tagged

You are not signed in. Login or sign up in order to post.