0

Please see the p-dropdown I modified the class City which now has one more property url. This property indicates the path of a component.

I have created the dropdown as

interface City {
    name: string;
    code: string;
    url:  string;
}

export class DropdownDemo {

cities: City[];

selectedCity: City;

constructor() {
    this.cities = [
        {name: 'New York', code: 'NY', url: 'app/ny'},
        {name: 'Rome', code: 'RM', url: 'app/rm'},
        {name: 'Washington DC', code: 'DC', url: 'app/dc'},
        {name: 'Houston', code: 'HT', url: 'app/ht'},
        {name: 'Paris', code: 'PR', url: 'app/pr'}
        ];
   }
}

The dropdown menu is in a navbar. The html page:

  <div class="collapse navbar-collapse>
    <ui class="narbar-nav mr-auto">
        <li class="nar-item>
            <a class="nav-link" href="#" routerLink="/api/ny">NY</a>
        </li>
        <li class="nar-item>
            <a class="nav-link" href="#" routerLink="/api/rm">RM</a>
        </li>
        <li class="nar-item>
            <a class="nav-link" href="#" routerLink="/api/dc">DC</a>
        </li>
        <li class="nar-item>
            <a class="nav-link" href="#" routerLink="/api/ht">HT</a>
        </li>
        <li class="nar-item>
            <a class="nav-link" href="#" routerLink="/api/pr">
                 <p-dropdown [options]="cities" [(ngModel)]="selectedCity" 
           optionLabel="name"></p-dropdown>
           </a>
         </li>
      </ui>
     </div>

The dropdown displays correctly. Now what I want is that if I click the dropdown menu item then it will go to the corresponding component. So I guess that maybe I have to bind href or routerLink somewhere. But I just don't know how?

UPDATE:

If I add a click event inside the p-dropdown element then navigating, the code seems working but the page is still on the component of the path api/pr.

Hello
  • 796
  • 8
  • 30

1 Answers1

0

you can maybe use the onChange($event),

  <p-dropdown [options]="cities" [(ngModel)]="selectedCity" optionLabel="name" (onChange)="onChange($event)"></p-dropdown>

when a city is clicked you will recive all the data, then you can use

router.navigate(['xxxxx']);

to go to the page you want, but first you need to set up a router !

Edit:

you need to change this :

<a class="nav-link" href="#" routerLink="/api/pr">
  <p-dropdown [options]="cities" [(ngModel)]="selectedCity" optionLabel="name"></p-dropdown>
</a>

to

<p-dropdown [options]="cities" [(ngModel)]="selectedCity" 
           optionLabel="name" (onChange)="onChange($event)"></p-dropdown>

then in your ts file you need to create a new methode like this :

onChange(event) {
    console.log('event :' + event);
    console.log(event.value);
    router.navigate([event.value.url]); // something like that

}
Numero3bis
  • 16
  • 1
  • 3