Rishi Bharadwaj
Rishi Bharadwaj

Reputation: 2086

how to make drop down menu not to reload the page on caret click in angular 2

I am working on an Angular 2 application and I have created a HTML component for menu bar following a bootstrap example. Whenever I click on the caret near Page 1 it reloads the whole page instead of just showing the child menu. What am I doing wrong?

MenuBar:

<nav class="navbar navbar-inverse" *ngIf="showNavBar">
    <div class="container-fluid">
        <div class="navbar-header">
            <a class="navbar-brand" href="#">Streams</a>
        </div>
        <ul class="nav navbar-nav">
            <li class="active"><a href="#">Home</a></li>
            <li class="dropdown">
                <a class="dropdown-toggle" data-toggle="dropdown" href="#">
                    Page 1
                    <span class="caret"></span>
                </a>
                <ul class="dropdown-menu">
                    <li><a href="#">Page 1-1</a></li>
                    <li><a href="#">Page 1-2</a></li>
                    <li><a href="#">Page 1-3</a></li>
                </ul>
            </li>
            <li><a href="#">Page 2</a></li>
            <li><a href="#">Page 3</a></li>
        </ul>
    </div>
</nav>

App.component.ts

import { Component } from 'angular2/core';
import { LoginComponent } from './home/login.component';
import { WelcomeComponent } from './home/welcome.component';
import { HTTP_PROVIDERS }  from 'angular2/http';
import { RouteConfig, ROUTER_DIRECTIVES } from 'angular2/router';
import { TopNavbarComponent } from './navbar.component';

@Component({
    selector: 'cmt-app',
    template: `<div class='container'>
                    <navbar></navbar>
                    <router-outlet></router-outlet>
                </div>
            `,
    directives: [ROUTER_DIRECTIVES, TopNavbarComponent],
    providers: [HTTP_PROVIDERS]
})

@RouteConfig([
        { path: '/login', name: 'Login', component: LoginComponent, useAsDefault: true },
        { path: '/welcome', name: 'Welcome', component: WelcomeComponent }
])

export class AppComponent {
    
}

Upvotes: 3

Views: 4166

Answers (2)

rlcrews
rlcrews

Reputation: 3562

The issue is with using href and #. On click you are invoking a url route that your route configure is picking up. Do one of the two update your href to navigate to a view or don't use href=# and instead call a ng-click to then invoke the navigation.

Upvotes: 0

micronyks
micronyks

Reputation: 55443

Problem is with href="#". Try to use href="javascript:void(0)"

<a class="dropdown-toggle" data-toggle="dropdown" href="javascript:void(0)">
                    Page 1
                    <span class="caret"></span>
</a>

Upvotes: 5

Related Questions