简体   繁体   中英

How to get the selected value of multiple dropdown onclick a button in angular6

I have 2 dropdowns, I need to just get the selected value of those dropdown on click a save button in angular 6 or typescript.I know in jquery but here I am new to angular 6,can any one please help me.Here is the code below

app.component.html

<select class="select1">
    <option>country1</option>
    <option>country2</option>
    <option>country3</option>
    </select>

    <select class="select2">
    <option>state1</option>
    <option>state2</option>
    <option>state3</option>
    </select>
    <button (click)="save()">save</button>

app.component.ts

declare var require: any;
import { Component,OnInit, Output, EventEmitter } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
    toggle:boolean = true;  
    click : any;
    selectOneVal : any;
    selectTwoVal : any;

  ngOnInit(){

  }


save(){
    console.log(this.selectOneVal);
    console.log(this.selectTwoVal)
}

}

I think you need to read about forms in Angular here

app.component.html

<div style="text-align:center">
  <select class="select1" [(ngModel)]="selectOneVal">
    <option value="country1">country1</option>
    <option value="country2">country2</option>
    <option value="country3">country3</option>
  </select>

  <select class="select2" [(ngModel)]="selectTwoVal">
    <option value="state1">state1</option>
    <option value="state2">state2</option>
    <option value="state3">state3</option>
  </select>
  <button (click)="save()">save</button>
</div>
<small>
  selectOneVal: {{ selectOneVal}}
</small>
<br/>
<small>
  selectTwoVal: {{ selectTwoVal}}
</small>

app.component.ts

import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  title = "CodeSandbox";
  toggle: boolean = true;
  click: any;
  selectOneVal: any;
  selectTwoVal: any;

  ngOnInit() {
    this.selectOneVal = "country1";
    this.selectTwoVal = "state1";
  }

  save() {
    console.log(this.selectOneVal);
    console.log(this.selectTwoVal);
  }
}

app.module.ts

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";

import { AppComponent } from "./app.component";
import { FormsModule } from "@angular/forms";
@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, FormsModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

here is the working answer on codesandbox

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM