Search code examples
jsonangulardropdownnavigationbar

How do I retrieve the user selected option from my dropdown list?


I have created a nav-bar which consists of a dropdown list. How do I retrieve the user selected option and display it in my Home component? The list items displayed are directly from a JSON file and I am not using the "select-option" tags for it. Is there anyway to do this with my code?

Header.component.html

<nav class="navbar navbar-expand-sm">
                    <div class="container-fluid">
                  <ul class="nav navbar-nav">
                      <li class="dropdown">
                          <a class="navbar-brand" href="#room" class="dropdown-toggle" data-toggle="dropdown" role="button"> Rooms </a>
                          <ul class="dropdown-menu" >
                              <li  *ngFor="let room of room_list.rooms">
                                   <a class="navbar-brand" href="#room"  [routerLink]="['./room']" routerLinkActive="router-link-active">{{room.name}}</a> 
                              </li>
                          </ul>
                      </li>
                      <li>
                        <a class="navbar-brand" href="#home" [routerLink]="['/']" routerLinkActive="router-link-active"  >Home</a>
                      </li>
</ul>
      </div>
   </nav>

Header.component.ts

export class HeaderComponent implements OnInit {

  room_list: any;
  constructor() { 
  }

  ngOnInit() {
    //this.room_list = roomlist.default;

    this.room_list =JSON.stringify(roomlist.default);
    this.room_list=JSON.parse(this.room_list);
    console.log(roomlist);
  }

Solution

  • For your issue related to @freddy 's answer @V_stack

    <li .. (click)="selectedRoom(room)" (blur)= "DropdownBlur = true " >
    

    (blur) will lose focus of drop-down after the condition written after it will be true.

    TS file, initialize DropdownBlur with false and set it to true when you want to close the drop-down

    DropdownBlur = false;
    ...
    selectedRoom(room):void {
    console.log(room);
    this.DropdownBlur = true;
    }