簡體   English   中英

如何從頁面加載的下拉列表中獲取選定的值和文本,然后單擊具有 angular 8 響應形式的按鈕

[英]How to get the selected value and text from a dropdown on page load and on click a button with reactive form in angular 8

我有一個下拉列表,其數據來自循環。在這里我需要在加載時獲取選定的值和選定的文本,然后單擊跨度。我在這里使用反應形式。當我使用值時,選定的下拉列表默認為空選擇。 這是下面的代碼

主頁.component.html

<div>
<form [formGroup]="registerForm">
<select formControlName="title" class="form-control">

                        <option *ngFor="let grpdata of group" value="{{grpdata.groupid}}">{{grpdata.groupname}}</option>

                    </select>
 </form>
</div>
<p>home works!</p>
<div><span (click)="getSelectedVal()">Click here</span></div>

home.component.ts

import { Component, OnInit } from '@angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
declare var $: any;
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  getListData: any;
  registerForm: FormGroup;
  group:any;
  constructor(private commonserviceService: CommonserviceService,private formBuilder: FormBuilder) { }

  ngOnInit() {
     this.registerForm = this.formBuilder.group({
            title: ['', Validators.required]
     })
      this.group = [{"groupid":1,"groupname":"project1"},{"groupid":2,"groupname":"project2"},{"groupid":3,"groupname":"project3"}];
      console.log('selected value is')
      console.log('selected text is')
  }
 getSelectedVal(){
     console.log('selected value is on click is')
     console.log('selected text is on click is')
 }
}

嘗試這個:

getSelectedVal() {
   console.log("selected value is on click is", this.registerForm.get("title").value);
}

工作演示

UIappDeveloper,分兩步做:

 getSelectedVal(){
   const value=this.registerForm.get('title').value; //get the value
   const status=this.statusdata.find(v=>v.groupid==value) //use "find"
                //status can be null, so I use ternary operator
                //else you are trying to get null.groupname and give you error
   console.log("value=",value,"status=",status?status.groupname:null)

 }

暫無
暫無

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

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