我有一个下拉列表,其数据来自循环。在这里,我需要获取选定的值和选定的文本,并在加载时单击跨度。我在这里使用反应形式。当我使用值时,选定的下拉列表即将到来默认选择为空。这是下面的代码
<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>
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')
}
}
答案 0 :(得分:0)
尝试一下:
getSelectedVal() {
console.log("selected value is on click is", this.registerForm.get("title").value);
}
答案 1 :(得分:0)
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)
}