Clicking on submenu, in a sidebar, go to a url with Material Design using Angular 4

955 Views Asked by At

I am working on a book collection program and I have a static sidebar which will have options and when you click on some of the options it sends you to a url.

I can't get the going to url part to work.

So I just have a sidenav, then a menu item called Store and then a submenu with an item called Amazon.

There may be typos, as I typed this as the code is on a different computer. Basically, how do I get where a submenu will send me to a url? I can do it from the menu item.

<md-sidenav #sidenav mode="side" opened="true" class="app-sidenav">
  <md-nav-list>
    <button md-list-item>Book Choices</button>
    <button md-button>
      <span md-list-item
         [mdMenuTriggerFor]="amazon">Stores</span></button>
  </md-nav-list>
</md-sidenav>

<md-menu #amazon>
  <button md-button>
    <span md-menu-item>
     <span (click)="'http://amazon.com'">Amazon</span>
    </span>
  </button>
</md-menu>
3

There are 3 best solutions below

4
On BEST ANSWER

this thing (click)="'http://amazon.com'" does nothing at all since you just passed a string.

have you tried (click)="window.open('http://amazon.com', '_blank')"?

or create a function that does the window.open(parameter)

openlink(url: string)
{
  window.open(string, "_blank");
}

// HTML attribute
(click)="openlink('http://amazon.com')"
0
On

You cannot navigate to a url using this expression (click)="'http://amazon.com'". You need to use window.location.href or window.open method. Here is how you can do that:

<md-menu #amazon>
  <button md-button>
    <span md-menu-item>
     <span (click)="gotoUrl('http://www.amazon.com')">Amazon</span>
    </span>
  </button>
</md-menu>

in your typescript code, define the gotoUrl() method:

gotoUrl(url:string){
    window.location.href=url;
}

if you want to open the url in a new tab in the browser, then use this code:

gotoUrl(url:string){
    window.open(url, "_blank");
}
0
On

So while you can use (click) events in angular, if all you need to do is navigate to another url you can always just use good old html and an anchor link. If that's all your looking for keep it simple

<md-menu #amazon>
  <button md-button>
    <a md-menu-item href="http://amazon.com">
     Amazon
    </a>
  </button>
</md-menu>

If you still want to use a click you can, and the answer below was correct it just had a typo

So add a method in your component like:

goToUrl(url: string) {
    window.open(url);
}

And then in your view

<md-menu #amazon>
    <button md-button>
        <span md-menu-item (click)="goToUrl('http://amazon.com')">
        Amazon
        </span>
     </button>
</md-menu>