Skip to content Skip to sidebar Skip to footer

How To Get The Selected Option Of Dropdown On Click Of A Button In Angular 7

I have a dropdown that contains a few options coming from a loop,I need to get the selected option(not value) on click of a button. I tried with ngModel but I was able to get the v

Solution 1:

Just use ngModel to bind to the selected value. Since you want to get both id and the name from the selected option, it would be better if you get the entire object that was selected. You can do this using ngValue (Source: docs).

<select [(ngModel)]="selectedGroup"><option *ngFor="let group of groups" [ngValue]="group">{{group.name}}</option></select>
selectedGroup: any;

getVal() {
    console.log(this.selectedGroup); // returns selected objectconsole.log(this.selectedGroup.id); // returns selected option's idconsole.log(this.selectedGroup.name); // returns selected option's name
}

Solution 2:

Try like this:

Template:

<div><select [(ngModel)]="selectedgroup"><option *ngFor="let group of groups">{{group.name}}</option></select></div><inputtype="button" (click)="getVal()"value="submit"/>

Typescript:

selectedgroup: anygetVal() {
    console.log(this.selectedgroup)
    console.log(this.groups.filter(x => x.name == this.selectedgroup)[0].items)
  }

See Stackbiltz Demo

Solution 3:

        import { Component } from'@angular/core';
@Component({
selector: 'app-pager',
template: `
<div><select (change)="Selected($event)"><option *ngFor="let group of groups" [value]="group.name">{{group.name}}</option></select></div>
<input type="button" (click)="getVal()"value="submit"/>
<h4 [hidden]="hide">the name selected : {{ selected }} OR for click button : {{ button }} </h4>
`
})
export classPagerComponent {

selected : string = '';
button : string = '';

hide : boolean = true;
  Selected(event: any){
    //update the uithis.selected = event.target.value;
    this.hide=false;
  }
// or you can use the button :
getVal(){
this.button=this.selected;
}
groups=[
  {
    "name": "select your chois",
    "items": ""
  },
     {
       "name": "pencils",
       "items": "red pencil"
     },
     {
       "name": "rubbers",
       "items": "big rubber"
     },
     {
       "name": "rubbers1",
       "items": "big rubber1"
     }
  ];

}

    //you can give a value groups.name and working with $event 

Post a Comment for "How To Get The Selected Option Of Dropdown On Click Of A Button In Angular 7"