In the following example I have a simple dropdown list which contains list of customers. When you select a customer from the dropdown list, I need followings to be done.
- Selected customer name should be shown in the
"txtCustomerName"text box. - Selected customer name should be shown in the
"spnCustomerId"span element (I have done it in a way and I want to make sure if I'm doing it in a right way with the Reactive Forms).
In addition to above, I'm getting "ERROR TypeError: control.registerOnChange is not a function" error when the page is loaded. I found following similar post on stackoverflow but I couldn't find solid answer for the issue I'm facing.
ERROR TypeError: control.registerOnChange is not a function
ERROR TypeError: control.registerOnChange is not a function --> formControlName
My component class looks like this
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
public myForm: FormGroup;
public allCustomers: Customer[] = new Array();
constructor(private formBuilder: FormBuilder) {}
ngOnInit(): void {
this.myForm = this.formBuilder.group({
selectedCustomer: this.formBuilder.group({
id: [],
name:['']
})
})
this.allCustomers.push(new Customer(0, "John"));
this.allCustomers.push(new Customer(1, "Kumar"));
this.allCustomers.push(new Customer(2, "Warma"));
this.allCustomers.push(new Customer(3, "Sabitha"));
}
changeCustomer(e) {
console.log(JSON.stringify(this.myForm.get('selectedCustomer').value));
}
}
export class Customer {
public id: number;
public name: string;
constructor(cusId: number, cusName: string) {
this.id = cusId;
this.name = cusName;
}
}
My html page looks like this
<form name="frmMain" [formGroup]="myForm">
<div>
<div>
All customers:
<select (change)="changeCustomer($event)" formControlName="selectedCustomer">
<option value="" disabled>Please select</option>
<option *ngFor="let cus of allCustomers" [ngValue]="cus">{{cus.name}}</option>
</select>
</div>
<br/>
<div>
Selected customer id :
<span id="spnCustomerId">{{myForm.get('selectedCustomer').value.id}}</span>
</div>
<div>
Selected customer name :
<!-- I need to show selected customer name in below text box -->
<input id="txtCustomerName" type="text"/>
</div>
</div>
</form>
Please see above example in stackblitz