I have a dropdown whose data is coming from loop.Here I need to get the selected value and selected text on page load and on click a span.I am using reactive form here.To make default selection I am using new FormControl(1) ,Every thing is working correct I am getting the result in console.But when I am removing first object of array from my json and reload the page its creating error,since I hardcoded to 1 in FormControl,if I change to FormControl(2) its working fine.But I need to pass it dynamically so that it can work with any number of object. Here is the code below and demo example I created https://stackblitz.com/edit/angular-lwrvvz?file=src%2Fapp%2Fapp.component.ts
app.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
registerForm: FormGroup;
statusdata: any;
constructor(private formBuilder: FormBuilder)
{
this.registerForm = this.formBuilder.group({
title: new FormControl(1)
});
}
ngOnInit() {
this.statusdata = [{"groupid":1,"groupname":"project1"},{"groupid":2,"groupname":"project2"},{"groupid":3,"groupname":"project3"}];
console.log('selected Value', this.registerForm.get('title').value);
console.log('selected name', this.statusdata.filter(v => v.groupid == this.registerForm.get('title').value)[0].groupname);
}
getSelectedVal(){
console.log('selected Value', this.registerForm.get('title').value);
console.log('selected name', this.statusdata.filter(v => v.groupid == this.registerForm.get('title').value)[0].groupname);
}
}
app.component.html
-----------------
<hello name="{{ name }}"></hello>
<p>
Start editing to see some magic happenss :)
</p>
<div>
<form [formGroup]="registerForm">
<select formControlName="title" class="form-control">
<option *ngFor="let grpdata of statusdata" value="{{grpdata.groupid}}">{{grpdata.groupname}}</option>
</select>
</form>
</div>
<p>home works!</p>
<div><span (click)="getSelectedVal()">Click here</span></div>