Angular 5中如何获取动态生成组件的下拉框选中值
Hey there! Let's figure out how to grab the selected values from those dynamically generated dropdowns in Angular. I’ve got two reliable approaches for you to try out:
Approach 1: Use FormArray (Recommended)
This method leverages Angular's reactive forms system, which is perfect for dynamic form scenarios—it handles state management, validation, and value tracking out of the box.
Step 1: Set up the FormArray in your component class
First, import the necessary form modules and initialize a form group with a form array to hold each dropdown's value:
import { Component } from '@angular/core'; import { FormBuilder, FormGroup, FormArray } from '@angular/forms'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html' }) export class YourComponent { myForm: FormGroup; port: any[] = []; // Replace with your actual port data constructor(private fb: FormBuilder) { // Initialize the form with an empty FormArray for origins this.myForm = this.fb.group({ origins: this.fb.array([]) }); } // Getter to access the FormArray easily get originsArray(): FormArray { return this.myForm.get('origins') as FormArray; } }
Step 2: Add new dropdown controls on "Add" button click
Create a method to push new form controls into the FormArray when the button is clicked:
addOriginDropdown() { // Add an empty control (or set a default value if needed) this.originsArray.push(this.fb.control('')); }
Step 3: Update your template to bind with the FormArray
Modify your template to loop through the FormArray and bind each dropdown to its corresponding form control:
<form [formGroup]="myForm"> <div formArrayName="origins"> <!-- Loop through each control in the FormArray --> <div *ngFor="let originCtrl of originsArray.controls; let i = index"> <select class="form-control" [formControlName]="i"> <option *ngFor="let CodeListPort of port" [value]="CodeListPort.codeListPortID"> {{CodeListPort.codeListPortID}} </option> </select> </div> </div> <button (click)="addOriginDropdown()">Add</button> <button (click)="getAllSelectedValues()">Get All Selected Values</button> </form>
Step 4: Retrieve all selected values
Add a method to fetch the values from the FormArray whenever you need them:
getAllSelectedValues() { const selectedPortIds = this.originsArray.value; console.log('Selected Port IDs:', selectedPortIds); // Use selectedPortIds for your business logic here }
Approach 2: Use ViewChildren & Component Communication
If you prefer not to use reactive forms, you can encapsulate the dropdown into a child component and use ViewChildren to access instances and track their values.
Step 1: Create a reusable dropdown child component
import { Component, Input, Output, EventEmitter, ViewChild, ElementRef } from '@angular/core'; @Component({ selector: 'app-port-dropdown', template: ` <select #portSelect class="form-control" (change)="onValueChange($event.target.value)"> <option *ngFor="let CodeListPort of port" [value]="CodeListPort.codeListPortID"> {{CodeListPort.codeListPortID}} </option> </select> ` }) export class PortDropdownComponent { @Input() port: any[]; @Output() valueUpdated = new EventEmitter<string>(); @ViewChild('portSelect') portSelect: ElementRef<HTMLSelectElement>; // Emit value changes when the dropdown selection changes onValueChange(selectedValue: string) { this.valueUpdated.emit(selectedValue); } // Method to get the current selected value on demand getCurrentValue(): string { return this.portSelect.nativeElement.value; } }
Step 2: Use the child component in your parent component
import { Component, ViewChildren, QueryList, AfterViewInit } from '@angular/core'; import { PortDropdownComponent } from './port-dropdown.component'; @Component({ selector: 'app-parent-component', templateUrl: './parent-component.component.html' }) export class ParentComponent implements AfterViewInit { port: any[] = []; // Your port data dropdownCount: number[] = []; // Track how many dropdowns to render selectedValues: string[] = []; // Store real-time selected values @ViewChildren(PortDropdownComponent) dropdownComponents!: QueryList<PortDropdownComponent>; addDropdown() { this.dropdownCount.push(this.dropdownCount.length + 1); this.selectedValues.push(''); // Initialize empty value for the new dropdown } ngAfterViewInit() { // Listen to value changes from each dropdown this.dropdownComponents.forEach((comp, index) => { comp.valueUpdated.subscribe(value => { this.selectedValues[index] = value; console.log(`Dropdown ${index + 1} selected value:`, value); }); }); } getAllSelectedValues() { // Or fetch values directly from component instances const allValues = this.dropdownComponents.map(comp => comp.getCurrentValue()); console.log('All Selected Values:', allValues); } }
Step 3: Update the parent template
<app-port-dropdown *ngFor="let item of dropdownCount; let i = index" [port]="port" ></app-port-dropdown> <button (click)="addDropdown()">Add</button> <button (click)="getAllSelectedValues()">Get All Values</button>
Final Notes
The FormArray approach is strongly recommended because it integrates seamlessly with Angular's form ecosystem, making it easier to handle validation, form submission, and state management. The second method works well if you need more granular control over individual dropdown components.
内容的提问来源于stack exchange,提问作者Mukesh Kumar

