Black Dynamite
Black Dynamite

Reputation: 4147

Redirect in Angular 4.2.2 Programmatically

I'm building a toy app that has a Search page as the default, and then it has an Admin page. The admin page is called by clicking a button on the Search page. My code for that process is this:

  constructor( private searchResultService: SearchService, private router: Router) {
    ....
  }

  goToAdminLogin(ev): void
  {
    this.router.navigate(['adminLogin'])
  }

However, on the click of the Button the only thing that changes is the address bar.

In my app.module.ts, I have this:

RouterModule.forRoot([
  {
    path: 'search',
    redirectTo: '/search',
    pathMatch: 'full'
  },
  {
    path: 'adminLogin',
    component: AdminLoginComponent
  }
])

enter image description here

I've checked my console, and I don't see it spewing any error messages. Does anyone know why my redirect is going nowhere?

Any help is greatly appreciated.

EDIT: Adding the AdminLoginComponent:

My AdminLoginComponent looks like this:

import {Component, Inject, Input} from '@angular/core';
import {SearchService} from '../services/search.service';
import {SearchResponse} from '../remote/search-response';

@Component({
  selector: 'admin-login-component',
  templateUrl: './admin-login.component.html',
  styleUrls: ['./admin-login.component.css']
})
export class AdminLoginComponent {

  constructor( private searchResultService: SearchService)  {
  }
}

My 'admin-login.component.html' is very simple and looks like this:

<div>Hello</div>

EDIT: Solution

The solution thanks to Debbie K was to essentially drop my first UI out of my app.component.* and put it in a a sub component, similar to my admin-login setup. My app.component.html now looks like this:

<router-outlet></router-outlet>

Upvotes: 4

Views: 7370

Answers (2)

Hari Das
Hari Das

Reputation: 10864

This involves three simple steps:

  1. Import Router

    import {Router} from '@angular/router';

  2. In constructor

    constructor(private router: Router){}

  3. Navigate to different router

    this.router.navigate(['/about']);

Navigate to an URL

`this.router.navigateByUrl('/home');`

Upvotes: 10

DeborahK
DeborahK

Reputation: 60548

Try this:

this.router.navigate(['/adminLogin'])

And set up a hierarchy of router-outlets:

app.component.html

<router-outlet> <-- This one will show anything full page.

home.component.html

<header of menu stuff here>

<router-outlet> <-- This one will show anything within the header/footer

<footer stuff here>

Does my shorthand here make sense?

Upvotes: 11

Related Questions