Here is an example of an Angular form:
<div #myForm [formGroup]="myForm">
<select formControlName="productName" class="form-control">
<option value="">Select</option>
<option *ngFor="let item of productNames" [value]="item.value"
[textContent]="item.text"></option>
</select>
</div>
<button (click)="Print()">Print</button>
When I click the button, I want to retrieve the HTML content of the form so that I can use it elsewhere. To achieve this, I tried accessing the innerHtml using the form reference as shown below.
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
@Component({
selector: 'app-print-form',
templateUrl: './print-form.component.html',
styleUrls: ['./print-form.component.css']
})
export class PrintFormComponent implements OnInit {
myFormGrp: FormGroup;
productNames: any[];
@ViewChild('myForm') myForm: ElementRef<HTMLDivElement>;
constructor(private formBuilder:FormBuilder) { }
ngOnInit(): void {
this.productNames = [
{text: "aaa", value: "1"},
{text: "bbb", value: "2"},
{text: "ccc", value: "3"},
{text: "ddd", value: "4"}
];
this.myFormGrp = this.formBuilder.group({
productName: new FormControl({ value: '3', disabled: false })
});
}
Print(): void {
console.log(this.myForm.nativeElement.innerHTML);
}
}
However, the innerText does not include the selected value of the dropdown. How can I retrieve the selected values of the form controls?