[英]How to get selected value and selected text of a dropdown on click a button in angular 7
[英]How to get the selected value of multiple dropdown onclick a button in angular6
我有2個下拉菜單,我只需要單擊angular 6或typescript中的保存按鈕就可以得到這些下拉菜單的選定值。我在jquery中知道,但是這里我剛開始使用angular 6,請問有人可以幫助我。下面的代碼
<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>
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)
}
}
我認為您需要在此處閱讀有關Angular的表單
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上的有效答案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.