簡體   English   中英

如何在單擊 angular 7 中的按鈕時獲取下拉列表的選定值和選定文本

[英]How to get selected value and selected text of a dropdown on click a button in angular 7

我有一個下拉菜單 select,在這里單擊按鈕,我需要控制台選擇的文本(綠色..)和選擇的值(1..),我嘗試使用 ngmodel 但我只能捕獲值並且那里顯示空選項在 select 字段中。這是下面的代碼,

home.component.html

<select>
<option *ngFor="let status of statusdata" value="{{status.id}}">{{status.name}}</option>
</select>
<button type="submit" (click)="register()" class="btn btn-primary mr-1">Register</button>

home.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit { 
    dotsh:any;
    hoverIndex:number = -1;
    groups:any;
    test:any;
 constructor(private formBuilder: FormBuilder) {


     }
     onHover(i:number){
 this.hoverIndex = i;
}
     columns = ["name", "Items","status"];



  ngOnInit() {
      this.test = false;
      this.statusdata = [{"id":1,"name":"green"},{"id":2,"name":"red"},{"id":3,"name":"yellow"}];
} 

register(){
    console.log('selected Value');
    console.log('selected name');
}


}

如果您想要在選擇時將整個 object 存儲為一個值,您可以試試這個:

<select [(ngModel)]="value">
  <option *ngFor="let status of statusdata" [ngValue]="status"> 
   {{status.name}}</option>
</select>

然后在你的組件中聲明變量值,或者讓它未定義,或者將它分配給你想要的值(它需要是整個對象)。 例如:

export class HomeComponent implements OnInit { 
  statusdata = [{"id":1,"name":"green"},{"id":2,"name":"red"},{"id":3,"name":"yellow"}];
  value = statusdata[0];
  ....

這應該默認為選擇的第一個選項。 然后,如果您只想打印該值:

console.log(this.value.id);
console.log(this.value.name);

為了達到預期的效果,請使用以下選項,在 component.html 和 commponent.ts 中使用 Formbuilder、FormGroup 和 Form Control 名稱

組件.html

  1. 使用表單名稱作為[formGroup]="profileForm"
  2. 為 select 設置 formControlName 即formControlName="name"

`組件.ts
3.聲明formgroup並使用formbuilder初始化名稱

profileForm: FormGroup
 constructor(private formBuilder: FormBuilder) {
this.profileForm = this.formBuilder.group({
    name: new FormControl(1)
});  

4. 在按鈕上單擊使用this.profileForm.get('name').value獲取值

register(){
    console.log('selected Value', this.profileForm.get('name').value);
    console.log('selected name', this.statusdata.filter(v => v.id == this.profileForm.get('name').value)[0].name);
}

示例工作代碼供參考 - https://stackblitz.com/edit/angular-unnal4?file=src/app/app.component.ts

有關反應式 forms - https://angular.io/guide/reactive-forms的更多詳細信息,請參閱此鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM