如何在angular6中单击按钮时获得多个下拉列表的选定值

时间:2019-06-16 06:48:22

标签: html typescript angular6

我有2个下拉菜单,我只需要单击角度6或打字稿中的保存按钮即可获得这些下拉菜单的选定值。我在jquery中知道,但这里我对角度6还是陌生的,请问有人可以帮助我。这是下面的代码

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)
}

}

1 个答案:

答案 0 :(得分:0)

我认为您需要阅读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 {}

这是codesandbox

上的有效答案